Java arrays only allow subscripts to range between 0 and N-1 for an array of size N.
The class below aims to remove that constraint by allowing the class user to specify the valid subscripts for a one dimensional array of integers.
public class BoundedIntArray {
private int[] array;
// further state required here
public BoundedIntArray() {...}
public BoundedIntArray(int high) {...}
public BoundedIntArray(int low, int high) {...}
public int length() {...}
public int getElement(int index) {...}
public void putElement(int index, int value) {...}
public void resize(int low, int high) {...}
}
This is a question I was given in a recent exam. I'm struggling to understand quite what the problem is and what the above class is trying to accomplish.
What's wrong with only being allowed to range between 0 and N-1? Why would you want to exceed the size of the array and go beyond N or <0?
What do low and high refer to?
These are the exam questions:
a). The class needs further private members to identify the upper and lower bounds of the array. Provide appropriate declarations for this state. [4 marks]
b). Supply an implementation of the three constructors for the BoundedIntArray class
[6 marks]c). Provide an implementation for each method (with appropriate exceptions) for the BoundedIntArray class.
[15 marks]d). Explain how to generalise this class so that arrays of any type can be used rather than just int’s.
[5 marks]
1 Answer 1
A real world example might be waist sizes. Men's shorts might come in sizes from 28 inches to 50 in 1-inch increments. Instead of everywhere in your program saying, sizes[i + 27]
you create an "array" with indicies 28-50 (and thus size=21) and not have to worry about offsets.
BoundedIntArray sizes = new BoundedIntArray(28, 50);
void addToCount(int size) {
int count = sizes.get(size);
sizes.set(size, count + 1);
}
Presumably the BoundedIntArray would allocate an array when it is constructed of a suitable size to never throw an IndexOutOfBoundsException for the defined range.
-
Why is there no size declaration in private int[] array;?M-R– M-R2016年07月01日 20:26:54 +00:00Commented Jul 1, 2016 at 20:26
-
@MartinRand That's just Java syntax. If you want an array of 6 items you say
private int[] myArray = new int[6];
The size of the array is not part of the type. What you are asking for is called a "dependent type." If you want that, look at Idris. idris-lang.orgGlenPeterson– GlenPeterson2016年07月01日 20:29:45 +00:00Commented Jul 1, 2016 at 20:29 -
If the lower bound is, say, 28, wouldn't we be wasting memory for 0-28, which is declared but not used?M-R– M-R2016年07月01日 20:42:03 +00:00Commented Jul 1, 2016 at 20:42
low
andhigh
appear to be the lowest and highest numbers that you can pass as anindex
togetElement
andputElement
.low
tohigh
instead of0
ton
. This is probably to calm down all those people who throw tantrums when confronted with the fact that array indexing is 0-based in most (popular) languages.