List

advertisement
And the list goes on and on and on….
 Like an array, a List is set up to store multiple items.
But it has several advantages:
1. It can be dynamically expanded to make room for
more items.
2. Items can be removed and inserted anywhere with
ease.
3. It has several other methods such as contains which
gives it much more utility than an array.
4. The one disadvantage is that it can not store
primitives. But there is a work around to this which
we will cover latter.
 There are several ways that Lists are set up such. There
are ArrayLists, LinkedLists, Stack, Vector, etc.
 Each implementation has the same interface.
 But encapsulation allows us to have different
implementations.
 The one specific type of list that we will be using will
be an ArrayList.
 It’s implementation includes using an array inside the
ArrayList class.
 But things like expanding the ArrayList, adding items
in order, and other things are taken care of for us
inside the ArrayList class. Encapsulation for the win!
 Given the following items were in an ArrayList called letters:





{“A”, “B”, “C”, “D”, “E”, “F”}
This is how the ArrayList would change after the following
method calls:
letters.add(“X”);
{“A”, “B”, “C”, “D”, “E”, “F”, “X”}
letters.add(1, “Y”);
{“A”, “Y”, “B”, “C”, “D”, “E”, “F”, “X”}
letters.remove(4);
{“A”, “Y”, “B”, “C”, “E”, “F”, “X”}
letters.set(0, “Z”);
{“Z”, “Y”, “B”, “C”, “E”, “F”, “X”}
 Lists by default are designed to store any object.
 This allows you to add an object of any type to a list.
 But this can be problematic since you can not be
certain of the type of the object that you obtain from
the list.
 Think of it like having a big box that you can put all
different types of household items into. It is
convenient to do so until you want a hammer and you
pull out a scarf.
 You can restrict the type of objects that a list stores in the
following manner
 Declared without a type:




ArrayList carLot = new ArrayList();
carLot.add(new Car(“Camry”));
carLot.add(new Toy(“Elmo”));
((Car)carLot.get(0)).run();
 Declared with a type:
 ArrayList<Car> carLot = new ArrayList<Car>();
 carLot.add(new Car(“Camry”));
 carLost.get(0).run();
 In the second example, only Car objects can be added to the list
and you don’t have to cast objects returned from the list as a Car
to call Car methods
Download