Learn Java

 

Lists

Lists are an interface from the Java Collections Framework

Lists are ordered sequences of items. Each item has a position in the list (an index) starting from zero, and items can be inserted, added and removed from the list

Lists can have duplicate entries and can also if necessary have a natural ordering such as alphabetical

Lists are homogeneous - all the elements have to be of the same type

Lists are a subinterface of the Collection interface

The table below shows some methods of the Collection interface

MethodDescription
addAll(Collection c)Adds all the elements of the specified collection to the receiver
add(E o)Adds the specified element to the collection
remove(Object o)Remove the specified element from the collection
clear()Removes all elements from the collection
size()Returns the number of elements in the collection
contains(Object o)Returns true if the collection contains the specified element
isEmpty()Returns true if the collection is empty

List can implement all of the methods of the Collection interface because List is a subinterface of the Collection interface

So to create a list containing instances of the Car class we could use the following statement

List<Car> myCarList = new ArrayList<Car>();

List is the interface, ArrayList is a class that implements the List interface and the element type is placed between the angled brackets, in this case instances of the class Car

We can add elements to our car list and print the size as follows

List<Car> myCarList = new ArrayList<Car>();

myCarList.add("VW Golf");

myCarList.add("Peugot 206");

myCarList.add("BMW 525");

System.out.println(myCarList.size());

Elements can also be inserted into a list at a specified index as follows

myCarList.add(2, "Ford Capri");

This will move "BMW 525" up one in the list to index 3

We can also get the element at a specific index and place the value into a variable as follows

String selectedCar = myCarList.get(1);

In a similar way we can remove an element from the list as follows

String removedCar - myCarList.remove(2);

We may need to find the index of a specific element, we can find the first occurrence of the element (should there be duplicates) as follows

int firstPosition = myCarList.indexOf("VW Golf");

To find the last occurrence of the element in the list use a statement similar to the following

int lastPosition = myCarList.lastIndexOf("VW Golf");

To replace an element in a list do something like the following

myCarList.set(1, "Fiat Punto");

We can interate through a list as follows

for (String eachElement : myCarList)

{

System.out.println(eachElement);

}

 

Previous Page Page 5 Next page

 

Page 1 2 3 4 5 6 7