Java Reference
In-Depth Information
A client will also want the ability to access individual elements of the list.
Internally, you access the list elements by referring to the array called elementData .
Again, you don't want to break encapsulation by giving a client direct access to this
field. Instead you can introduce another accessor method for examining the value
stored at a given index:
public int get(int index) {
return elementData[index];
}
Eventually, we want to make sure that this method can't be used by a client to
access any of the vacant array elements (elements beyond the size of the list), but this
simple version will do for now.
Dealing with the Middle of the List
So far we have explored how to add a value at the end of a list, but often a client is inter-
ested in dealing with values in the middle of the list. The client might want to search for
the location of values or add them to or remove them from the middle of the list.
Let's begin with the task of searching for the location of a value in a list. The
client could use the size and get methods to locate a value. But if it seems likely
that a client will want to perform frequent searches for the locations of values, then it
makes more sense to include the ability to do this as a method inside the class. That
way, it will be readily available to all clients of the class.
In Chapter 7 we wrote the following code to find the index of the first occurrence
of a value in an array of integers:
public static int indexOf(int[] list, int target) {
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
return i;
}
}
return -1;
}
This method is fairly easily converted from a static method to an instance method,
as you did with print . To achieve the conversion, replace the array parameter with
references to the elementData field and, instead of using the length of the array as a
loop bound, use the size field so that the method searches only elements of the array
that are currently in use:
public int indexOf(int value) {
for (int i = 0; i < size; i++) {
if (elementData[i] == value) {
 
Search WWH ::




Custom Search