Java Reference
In-Depth Information
How do you write this method? You don't want to duplicate the code that you
included in indexOf , so instead you'll call indexOf . Remember that it returns a
value of -1 if the value is not found, so you can test whether or not indexOf returned
an index that is greater than or equal to 0 :
public boolean contains(int value) {
if (indexOf(value) >= 0) {
return true;
} else {
return false;
}
}
This version violates Boolean Zen, which was covered in Chapter 5. You can simply
return the value of the expression, rather than including it in an if/else statement:
return indexOf(value) >= 0;
Thus, the method ends up being a single line of code:
public boolean contains(int value) {
return indexOf(value) >= 0;
}
Another common method in the Java collections framework is called isEmpty . It
returns a boolean value indicating whether or not the list is empty. This is another
method that can be written concisely as a one-line method using the value of the
size field:
public boolean isEmpty() {
return size == 0;
}
Again, you don't need an if/else statement; you can simply return the value of
the boolean expression.
So far you have included methods to add values to and remove values from the
list, but sometimes you simply want to replace the value at a certain location with
some new value. This operation is referred to as the set method and is easy to imple-
ment. You have to remember to include a call on checkIndex because the method
has a precondition that is similar to that of get and remove :
public void set(int index, int value) {
checkIndex(index);
elementData[index] = value;
}
 
Search WWH ::




Custom Search