You are on page 1of 27

Collections

Collections
• A collection is simply somewhere to put a group of
objects
• We have already looked at arrays, which allow us to
group together objects and reference them by index
• Many of the principles that apply to arrays apply to
other collections
• The other collection classes are more flexible and
easier to use than arrays
• All of the different collection classes allow you to
store objects inside them and to retrieve and
manipulate those objects
Collections
• When you are programming there are endless uses
for collections
• These simply mirror the way that objects are
grouped and collected together in the real world
• You might have a list of students, a list of favourite
television programmes, a list of items to buy at the
supermarket or a list of times your local squash court
is available for booking
Collections
• Java provides a number of different collection
classes, each of which has slightly different
characteristics
• You need to become familiar with each of them so
that you know which to use in different situations
ArrayList
• An ArrayList is like an array, which is not fixed in
length.
• ArrayLists are more flexible than arrays.
• You can use an enhanced for loop to get objects out
of an ArrayList
ArrayList
• Declaring an array list is easy
ArrayList <Student> myClass = new ArrayList <Student> ();

• Sometimes you may see this

ArrayList myClass = new ArrayList ();

• But that is now out of date – so don’t use it


ArrayList
• Adding things to an ArrayList is easy
//create student
Student s1 = new Student("Fred", "Edinburgh", 21, 123456);

//create array list


ArrayList <Student> myClass = new ArrayList <Student> ();

//add student
myClass.add(s1);
public class DemoArrayList {
public static void main(String[] args) {

Student s1 = new Student("Fred", "Edinburgh", 21, 123456);


Student s2 = new Student("Mary", "Glasgow", 21, 121212);
Student s3 = new Student("David", "Livingston", 21, 232323);

//create array list


ArrayList <Student> myClass = new ArrayList <Student> ();

//add students
myClass.add(s1);
myClass.add(s2);
myClass.add(s3);

//display all students


for(Student tempStudent : myClass) {
tempStudent.displayDetails();
}

}
}//end class
Method name Description
add(int index, Object Insert the object obj in the array list at
obj) position index. Objects beyond index
are displaced.
addAll(Collection c) Appends all of the elements in
collection c to the array list
clear() Removes all of the elements from the
list
contains(Object obj) Returns true if the array list contains
the object obj, otherwise returns false
get(int index) Returns the element at position index
size() Returns the number of elements in the
list
Linked List
• A LinkedList provides methods to add elements at
the beginning and end of the list and to remove
elements from the beginning and end of the list
• This allows LinkedLists to be used as stacks or
queues
• Stacks and queues are very important in computing
Linked List
Method Name Description
addFirst(Object o) Adds the object o to the front of the
list
addLast(Object o) Adds the object o to the end of the list
getFirst() Returns the first element in the list
getLast() Returns the last element in the list
removeFirst() Removes the first element from the list
removeLast() Removes the last element from the list
Linked List
public class Plane {
private int flightNumber;

public Plane(int flightNumber) {


this.flightNumber = flightNumber;
}

public int getFlightNumber() {


return this.flightNumber;
}

public void setFlightNumber(int flightNumber) {


this.flightNumber = flightNumber;
}
}
import java.util.LinkedList; //import LinkedList
public class AirTrafficControl {

private LinkedList <Plane> theLandingQueue = new LinkedList <Plane> ();

public void add(Plane plane) {


this.theLandingQueue.addLast(plane);
}
public void sizeOfQueue() {
System.out.print("Queue is " +this.theLandingQueue.size() +"\n");
}

public void whoIsNextToLand() {


System.out.print("Next to land is " +
this.theLandingQueue.peekFirst().getFlightNumber() +"\n");
}

public void land() {


this.theLandingQueue.removeFirst();
}
} //end class
public class DemoLinkedList {
public static void main(String[] args) {

AirTrafficControl theATC = new AirTrafficControl();


Plane p1 = new Plane(123);
Plane p2 = new Plane(345);
Plane p3 = new Plane(678);

theATC.add(p1);
theATC.add(p2);
theATC.add(p3);

theATC.sizeOfQueue();

theATC.whoIsNextToLand();

theATC.land();

theATC.whoIsNextToLand();
}
}//end class
Sets
• Sets do not hold duplicate objects. Other than
that they are just like a list
• There are two types of set: the HashSet and the
TreeSet
• Deciding which to use is easy – the HashSet is
fastest but does not order the elements and the
TreeSet is slowest but does order elements
Hash Sets
• The order of the objects is not guarenteed
• Optimised for speed
Tree Set
• All objects must be able to order themselves
• Adding objects that can’t order themselves will
cause the program to crash
public class DemoSets {
public static void main(String[] args) {
Student s1 = new Student("Fred", "Edinburgh", 21, 123456);
Student s2 = new Student("Mary", "Glasgow", 21, 121212);
Student s3 = new Student("David", "Livingston", 21, 232323);

HashSet <Student> myClass = new HashSet <Student> ();

myClass.add(s1);
myClass.add(s2);
myClass.add(s3);
System.out.print("Size of class is " +myClass.size() +"\n");

myClass.add(s1); //try adding an exisiting object


System.out.print("Size of class is " +myClass.size() +"\n");

if (myClass.add(s1)) { //check return value


System.out.print("Added");
}
else {
System.out.print("Rejected");
}
}
}//end class
Sets
public class DemoSets {
public static void main(String[] args) {
Student s1 = new Student("Fred", "Edinburgh", 21, 123456);
Student s2 = new Student("Mary", "Glasgow", 21, 121212);
Student s3 = new Student("David", "Livingston", 21, 232323);

TreeSet <Student> myTreeSet = new TreeSet <Student> ();


myTreeSet.add(s1); //program crashes here!
myTreeSet.add(s2);
myTreeSet.add(s3);

System.out.print("Size of class is " +myTreeSet.size() +"\n");

}
}//end class
Maps
• A Map stores associations between two objects
• A key, which must be unique, is associated with a
value, which does not have to be unique
• A map operates much like a real world dictionary
with the key being the word you look up and the
value being the definition
• There are two types of Map and it is easy to decide
which one to use
• A HashMap is fast and efficient but does not order
the keys
• The TreeMap has ordered keys
Hash Map
• The class HashMap is arguably the most important
class in the java.util package
• Creating a HashMap is easy

TreeMap <String, String> myData= new TreeMap <String, String> ();


Hash Map
• You can then add objects to the HashMap using the
put() method
myData.put("John", "0131-455-2741");
HashMap
 Notice that the order of the arguments is important
 The first argument is the key object and the second
argument is the value object

myData.put("John", "0131-455-4215");

Key Value
Hash Map
 The method get() allows you to specify a key and
retrieve the object associated with that key

String phoneNumber;
phoneNumber = myData.get("John");
Maps
import java.util.TreeMap;

public class DemoMaps {


public static void main(String[] args) {

Student s1 = new Student("Fred", "Edinburgh", 21, 123456);


Student s2 = new Student("Mary", "Glasgow", 21, 121212);
Student s3 = new Student("David", "Livingston", 21, 232323);

TreeMap <String, Integer> matricFinder = new TreeMap <String, Integer> ();

//add key/value pairs


matricFinder.put(s1.getName(), s1.getMaticulationNumber());
matricFinder.put(s2.getName(), s2.getMaticulationNumber());
matricFinder.put(s3.getName(), s3.getMaticulationNumber());

System.out.println("Matric number for " +s2.getName() +" is "


+matricFinder.get(s2.getName()));

//continued on the next slide


Maps
//continued from previous slide

//add student objects


TreeMap<String, Student> myClass = new TreeMap <String, Student> ();
myClass.put(s1.getName(), s1);
myClass.put(s2.getName(), s2);
myClass.put(s3.getName(), s3);

//retrieve all objects in alphabetical order


for(String tempStudentName : myClass.keySet()) {
myClass.get(tempStudentName).displayDetails();
}//end for loop

}//end main
}//end class
Tutorial Time
• Now it’s your turn ...

You might also like