Java Reference
In-Depth Information
you find them, an ArrayList is more efficient because it requires fewer
objects: the one array instead of one object for each element in the list.
You can also efficiently scan an ArrayList without creating an Iterator
object, by simply using an int as an index. This can be a good reason to
use an ArrayList for a list that will be scanned frequently.
Here is a Polygon class that stores a list of Point objects that are the
polygon's vertices:
import java.util.List;
import java.util.ArrayList;
public class Polygon {
private List<Point> vertices =
new ArrayList<Point>();
public void add(Point p) {
vertices.add(p);
}
public void remove(Point p) {
vertices.remove(p);
}
public int numVertices() {
return vertices.size();
}
// ... other methods ...
}
Notice that vertices is a List reference that is assigned an ArrayList ob-
ject. You should declare a variable to be as abstract a type as possible,
preferring the abstract List type to the implementation class ArrayList .
As written, you could change Polygon to use a LinkedList if that would be
more efficient by changing only one line of codethe line that creates the
list. All the other code can remain unchanged.
 
Search WWH ::




Custom Search