Java Reference
In-Depth Information
This modification completes the shifting, but you also have to store the new value
at the target index now that there is room for it, and you have to increment the size of
the list:
public void add(int index, int value) {
for (int i = size; i >= index + 1; i--) {
elementData[i] = elementData[i - 1];
}
elementData[index] = value;
size++;
}
Another Constructor and a Constant
The ArrayIntList class is shaping up nicely, but so far you have just a single con-
structor that constructs a list with a capacity of 100:
public ArrayIntList() {
elementData = new int[100];
size = 0;
}
This constructor isn't very flexible. What if clients want to manipulate a list of 200
values? What are they supposed to do? You don't want to force them to rewrite the code
just to use your class. That would be like having to open up a radio and rewire the
insides just to change the volume or the station. If there is some value like the capacity
that the client is likely to want to change, then you want to be sure to build in the flexi-
bility to allow the client to do so.
You can accomplish this flexibility by changing the constructor to take a parameter
that specifies the capacity of the list. You can then use that value when you construct
the array:
public ArrayIntList(int capacity) {
elementData = new int[capacity];
size = 0;
}
This modification allows a client to write lines of code like the following:
ArrayIntList list1 = new ArrayIntList(200);
Unfortunately, if this is your only constructor, then the client loses the ability to
write lines of code like the following:
ArrayIntList list2 = new ArrayIntList();
 
Search WWH ::




Custom Search