Java_Collection__1746604519
Java_Collection__1746604519
Ashish Thakur
Chapter Topics
Ashish Thakur 2
The Java Collection Framework
Ashish Thakur 3
The Main Types of Collections
• Lists
• Sets
• Maps
Ashish Thakur 4
Lists
Ashish Thakur 5
Sets
Ashish Thakur 6
Maps
Ashish Thakur 7
Part of the JCF Hierarchy
Ashish Thakur 8
Ashish Thakur 9
The Collection Interface
Ashish Thakur 10
Some Methods in the Collection Interface
Method Description
add(o : E) : boolean Adds an object o to the Collection. The method returns
true if o is successfully added to the collection, false
otherwise.
clear() : void Removes all elements from the collection.
Ashish Thakur 11
AbstractCollection
Ashish Thakur 12
Iterators
Ashish Thakur 13
The Iterator Interface
Ashish Thakur 14
Methods of the Iterator Interface
Method Description
Ashish Thakur 15
The List Interface
Ashish Thakur 16
List Interface Methods
Ashish Thakur 17
The List Interface Methods
add(index:int, el:E) : Adds the element el to the collection at the given index.
void Throws IndexOutOfBoundsException if index is negative,
or greater than the size of the list.
get(index:int):E Returns the element at the given index, or throws
IndexOutBoundsException if index is negative or greater
than or equal to the size of the list.
indexOf(o:Object):int Returns the least (first) index at which the object o is
found; returns -1 if o is not in the list.
lastIndexOf(o:Object):int Returns the greatest (last) index at which the object o is
found; returns -1 if o is not in the list.
listIterator():ListIterator< Returns an iterator specialized to work with List
E> collections.
remove(index:int):E Removes and returns the element at the given index;
throws IndexOutOfBoundsException if index is negative,
or greater than or equal to the size of the list.
set(index:int, el:E):E Replaces the element at index with the new element el.
Ashish Thakur 18
AbstractList
Ashish Thakur 19
ArrayList and Vector
Ashish Thakur 20
AbstractSequentialList and LinkedList
Ashish Thakur 21
Using the Concrete List Classes
Ashish Thakur 22
Example: ArrayList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};
// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);
Ashish Thakur 24
Example: LinkedList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new LinkedList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};
// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);
Ashish Thakur 26
The Iterator remove() method
Ashish Thakur 27
Using an Iterator
Ashish Thakur 28
ListIterator
Ashish Thakur 29
Some ListIterator Methods
Method Description
add(el:E):void Adds el to the list at the position just before the
element that will be returned by the next call to the
next() method.
hasPrevious():boolean Returns true if a call to the previous() method will
return an element, false if a call to previous() will throw
an exception because there is no previous element.
nextIndex():int Returns the index of the element that would be
returned by a call to next(), or the size of the list if
there is no such element.
previous():E Returns the previous element in the list. If the iterator
is at the beginning of the list, it throws
NoSuchElementException.
previousIndex():int Returns the index of the element that would be
returned by a call to previous(), or -1.
A call to next() puts the cursor just after the element returned,
and just before the element that will be returned by the next
call to next().
Ashish Thakur 31
Iterator and ListIterator Exceptions
Ashish Thakur 32
Example Use of a ListIterator
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String>();
String [ ] names = {"Ann", "Bob", "Carol"};
Ashish Thakur 33
Enhanced For Loop
Ashish Thakur 34
Sets
Ashish Thakur 35
The Set Part of the JCF Hierarchy
AbstractCollection
AbstractSet
HashSet TreeSet
LinkedHashSet
Ashish Thakur 36
The Set Part of the JCF
Ashish Thakur 37
HashSet
Ashish Thakur 38
Examples of Hashing Functions
Ashish Thakur 39
A Simplistic Hashing Function
Ashish Thakur 40
Implementation of a HashSet
Ashish Thakur 41
Implementation of a HashSet
Ashish Thakur 42
How a HashSet Works
• To add an element X, the hash code for X is used (as
an index) to locate the appropriate bucket. X is then
added to the list for that bucket. If X is already in the
bucket (The test is done using the equals method),
then it is not added.
Ashish Thakur 43
Efficiency of HashSet Operations
Ashish Thakur 44
HashSet Performance Considerations
Ashish Thakur 45
HashSet Capacity and Load Factor
Ashish Thakur 46
Some HashSet Constructors
Ashish Thakur 47
The hashCode() method
Ashish Thakur 48
Overriding the hashCode() Method
Ashish Thakur 49
HashSet Example 1
import java.util.*;
/**
This program demonstrates how to add elements
to a HashSet. It also shows that duplicate
elements are not allowed.
*/
public class HashSetDemo1
{
public static void main(String[] args)
{
// Create a HashSet to hold String objects.
Set<String> fruitSet = new HashSet<String>();
// Add some strings to the set.
fruitSet.add("Apple");
fruitSet.add("Banana");
fruitSet.add("Pear");
fruitSet.add("Strawberry");
// Display the elements in the set.
System.out.println("Here are the elements.");
for (String element : fruitSet)
System.out.println(element);
// Try to add a duplicate element.
System.out.println("\nTrying to add Banana to " +
"the set again...");
if (!fruitSet.add("Banana"))
System.out.println("Banana was not added again.");
// Display the elements in the set.
System.out.println("\nHere are the elements once more.");
for (String element : fruitSet)
System.out.println(element);
}
}
Ashish Thakur 50
A Car Class for Use With a HashSet
class Car
{
String vin, description;
public boolean equals(Object other) // Depends on vin only
{
if (!(other instanceof Car))
return false;
else
return vin.equalsIgnoreCase(((Car)other).vin);
}
Ashish Thakur 52
Use of the Car Class with a HashSet
public static void main(String [ ] args)
{
Set<Car> carSet = new HashSet<Car>();
Car [ ] myRides = {
new Car("TJ1", "Toyota"),
new Car("GM1", "Corvette"),
new Car("TJ1", "Toyota Corolla")
};
// Add the cars to the HashSet
for (Car c : myRides)
carSet.add(c);
GM1 Corvette
TJ1 Toyota
Note:
• The iterator does not return items in the order added to the
HashSet.
• The entry of the Toyota Corolla is rejected because it is equal
to an entry already stored (same vin).
Ashish Thakur 54
HashSet Example 2
import java.util.*;
/**
This program creates a HashSet, adds some
names to it, gets an iterator for the set,
and searches the set for names.
*/
public class HashSetDemo2
{
public static void main(String[] args)
{
// Create a HashSet to hold names.
Set<String> nameSet = new HashSet<String>();
// Add some names to the set.
nameSet.add("Chris");
nameSet.add("David");
nameSet.add("Katherine");
nameSet.add("Kenny");
// Get an iterator for the set.
Iterator it = nameSet.iterator();
Ashish Thakur 55
HashSet Example 2
// Display the elements in the set.
System.out.println("Here are the names in the set.");
while (it.hasNext())
System.out.println(it.next());
System.out.println();
// Search for "Katherine". We should find this
// name in the set.
if (nameSet.contains("Katherine"))
System.out.println("Katherine is in the set.");
else
System.out.println("Katherine is NOT in the set.");
// Search for "Bethany". We should not find
// this name in the set.
if (nameSet.contains("Bethany"))
System.out.println("Bethany is in the set.");
else
System.out.println("Bethany is NOT in the set.");
}
}
Ashish Thakur 56
HashSet Example 3
/**
The Car class stores a VIN (Vehicle Identification
Number) and a description for a car.
*/
public class Car
{
private String vin; // Vehicle Identification Number
private String description; // Car description
/**
Constructor
@param v The VIN for the car.
@param desc The description of the car.
*/
public Car(String v, String desc)
{
vin = v;
description = desc;
}
/**
getVin method
@return The car's VIN.
*/
public String getVin()
{
return vin;
}
Ashish Thakur 57
HashSet Example 3
/**
getDescription method
@return The car's description.
*/
public String getDescription()
{
return description;
}
/**
toString method
@return A string containing the VIN and description.
*/
public String toString()
{
return "VIN: " + vin +
"\tDescription: " +
description;
}
/**
hashCode method
@return A hash code for this car.
*/
public int hashCode()
{
return vin.hashCode();
}
Ashish Thakur 58
HashSet Example 3
/**
equals method
@param obj Another object to compare this object to.
@return true if the two objects are equal, false otherwise.
*/
public boolean equals(Object obj)
{
// Make sure the other object is a Car.
if (obj instanceof Car)
{
// Get a Car reference to obj.
Car tempCar = (Car) obj;
// Compare the two VINs. If the VINs are
// the same, then they are the same car.
if (vin.equalsIgnoreCase(tempCar.vin))
return true;
else
return false;
}
else
return false;
}
}
Ashish Thakur 59
HashSet Example 3
import java.util.*;
/**
This program stores Car objects in a HashSet and then
searches for various objects.
*/
public class CarHashSet
{
public static void main(String[] args)
{
// Create a HashSet to store Car objects.
Set<Car> carSet = new HashSet<Car>();
// Add some Car objects to the HashSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("448A69", "1965 Mustang"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
// Display the elements in the HashSet.
System.out.println("Here are the cars in the set:");
for (Car c : carSet)
System.out.println(c);
System.out.println();
Ashish Thakur 60
HashSet Example 3
// Search for a specific car. This one is in the set.
Car mustang = new Car("448A69", "1965 Mustang");
System.out.println("Searching for " + mustang);
if (carSet.contains(mustang))
System.out.println("The Mustang is in the set.");
else
System.out.println("The Mustang is NOT in the set.");
// Search for another car. This one is not in the set.
Car plymouth = new Car("911C87", "2000 Plymouth");
System.out.println("Searching for " + plymouth);
if (carSet.contains(plymouth))
System.out.println("The Plymouth is in the set.");
else
System.out.println("The Plymouth is NOT in the set.");
}
}
Ashish Thakur 61
LinkedHashSet
Ashish Thakur 62
TreeSet
Ashish Thakur 63
Order
Ashish Thakur 64
Examples of Natural Orders
Ashish Thakur 65
The Comparable Interface
Ashish Thakur 66
Using a TreeSet with Comparable Elements
Ashish Thakur 67
Sorting Strings Using a TreeSet
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
// Create TreeSet
Set<String> mySet = new TreeSet<String>();
// Add Strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
Ashish Thakur 68
The SortedSet Interface
Ashish Thakur 69
Comparators
Ashish Thakur 70
The Comparator Interface
Ashish Thakur 71
Using TreeSets with Comparators
A TreeSet that stores objects of a class that does not
implement Comparable must use a comparator to
order its elements.
Ashish Thakur 72
A Comparator for Ordering Strings in Reverse
Alphabetic Order
import java.util.*;
class RevStrComparator implements Comparator<String>
{
public int compare(String s1, String s2)
{
return - s1.compareTo(s2); // Note the negation operator
}
}
Ashish Thakur 73
Using a TreeSet to Sort Strings in Reverse
Alphabetic Order
public class Test
{
public static void main(String [ ] args)
{ // Create Comparator
RevStrComparator comp = new RevStrComparator();
Set<String> mySet = new TreeSet<String>(comp);
// Add strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
Ashish Thakur 74
TreeSet Example 1
import java.util.*;
/**
This program demonstrates how a TreeSet
sorts its elements in ascending order.
*/
public class TreeSetDemo1
{
public static void main(String[] args)
{
// Create a TreeSet and store some values in it.
SortedSet<String> mySet = new TreeSet<String>();
mySet.add("Pear");
mySet.add("Apple");
mySet.add("Strawberry");
mySet.add("Banana");
// Display the elements in the TreeSet.
System.out.println("Here are the TreeSet elements " +
"in ascending order:");
for (String str : mySet)
System.out.println(str);
// Add a new element to the TreeSet.
System.out.println("\nAdding Blueberry to the set.");
mySet.add("Blueberry");
// Display the elements again.
System.out.println("\nHere are the TreeSet elements " +
"again:");
for (String str : mySet)
System.out.println(str);
}
}
Ashish Thakur 75
TreeSet Example 2
import java.util.Comparator;
public class CarComparator<T extends Car>
implements Comparator<T>
{
public int compare(T car1, T car2)
{
// Get the two cars' VINs.
String vin1 = car1.getVin();
String vin2 = car2.getVin();
// Compare the VINs and return the
// result of the comparison.
return vin1.compareToIgnoreCase(vin2);
}
}
Ashish Thakur 76
TreeSet Example 2
import java.util.*;
/**
This program demonstrates how a TreeSet
can use a Comparator to sort its elements.
*/
public class TreeSetDemo2
{
public static void main(String[] args)
{
// Create a TreeSet and pass an instance of
// CarComparator to it.
SortedSet<Car> carSet =
new TreeSet<Car>( new CarComparator<Car>() );
// Add some Car objects to the TreeSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
carSet.add(new Car("448A69", "1965 Mustang"));
// Display the elements in the TreeSet.
System.out.println("Here are the cars sorted in " +
"order of their VINs:");
for (Car car : carSet)
System.out.println(car);
}
}
Ashish Thakur 77
Maps
The map stores the mappings based on the key part of the
mapping, in a way similar to how a Set collection stores its
elements.
Ashish Thakur 78
The Map Part of the JCF Hierarchy
Map
AbstractMap
HashMap TreeMap
LinkedHashMap
Ashish Thakur 79
The Map Interface
Ashish Thakur 80
Some Methods of the Map Interface
keySet() : Set<K> Returns the set of all keys stored in the map.
Ashish Thakur 81
Some Methods of the Map Interface
Ashish Thakur 82
Concrete Map Classes
Ashish Thakur 83
HashMap Example 1
import java.util.*;
/**
This program stores mappings in a HashMap and then
searches for various objects.
*/
public class CarHashMap1
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
Ashish Thakur 84
HashMap Example 1
// Search for the Mustang by its VIN.
System.out.println("\nSearching for the car with " +
"VIN " + mustang.getVin());
Car foundCar = carMap.get(mustang.getVin());
// If the car was found, display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("The Mustang is NOT in the set.");
// Search for another VIN. This one is not in the set.
System.out.println("\nSearching for the car with " +
"VIN 911C87");
foundCar = carMap.get("911C87");
// If the car was found display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("That car is NOT in the set.");
}
}
Ashish Thakur 85
HashMap Example 2
import java.util.*;
/**
This program retrieves a set of keys and a
collection of values from a HashMap.
*/
public class CarHashMap2
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
Ashish Thakur 86
HashMap Example 2
// Get a set containing the keys in this map.
Set<String> keys = carMap.keySet();
// Iterate through the keys, printing each one.
System.out.println("Here are the keys:");
for (String k : keys)
System.out.println(k);
// Get a collection containing the values.
Collection<Car> values = carMap.values();
// Iterate through the values, printing each one.
System.out.println("\nHere are the values:");
for (Car c : values)
System.out.println(c);
}
}
Ashish Thakur 87
HashMap Example 3
import java.util.*;
/**
This program retrieves the mappings from a HashMap
as a Set of Map.Entry objects.
*/
public class CarHashMap3
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
Ashish Thakur 88
HashMap Example 3
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
Ashish Thakur 89
HashMap Example 4
import java.util.*;
/**
This program retrieves the mappings from a
LinkedHashMap as a Set of Map.Entry objects.
*/
public class CarHashMap4
{
public static void main(String[] args)
{
// Create a LinkedHashMap to store Car objects.
Map<String, Car> carMap =
new LinkedHashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
Ashish Thakur 90
HashMap Example 4
// Put some mappings into the LinkedHashMap. In
// each mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
Ashish Thakur 91
HashMap Example 5
import java.util.*;
/**
This program displays the mappings stored in a
TreeMap. The mappings are displayed in ascending
key order.
*/
public class CarHashMap5
{
public static void main(String[] args)
{
// Create a TreeMap to store Car objects.
SortedMap<String, Car> carMap =
new TreeMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the TreeMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
Ashish Thakur 92
HashMap Example 5
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}
Ashish Thakur 93