Java Reference
In-Depth Information
In its place, include this line of code:
elementData = (E[]) new Object[capacity];
This new version compiles, but it generates a warning about using unsafe or
unchecked types. There's no real way to get around this because Java won't let you
construct a generic array. That means you can ignore this warning. In this case, it is
good to include an annotation for the method to indicate that you don't want it to
generate the warning for this method:
@SuppressWarnings("unchecked")
public ArrayList(int capacity) {
...
}
Annotations are special Java syntax that mark metadata on a class or method. They
give instructions to the compiler. This particular annotation is a way of telling the
compiler, “Don't generate the warning for this method because I'm aware of the
problem already.” There are many different kinds of annotations that you can include
in your Java programs, but we won't take time to explore them in this topic.
There is also a problem with the indexOf method. After you perform the substitu-
tion of E for int , here is the result:
public int indexOf(E value) {
for (int i = 0; i < size; i++) {
if (elementData[i] == value) {
return i;
}
}
return -1;
}
This version compiles and would work, but it has a very strict definition of equality.
It would require that the actual object you are searching for appears in the list. More
often, you want to use an equals comparison to see whether the value for which you
are searching is equal to some value in the list. You'll want to replace the following
bit of code from your method:
if (elementData[i] == value) {
...
}
You can replace it with the following:
if (elementData[i].equals(value)) {
...
}
 
Search WWH ::




Custom Search