Collections - in - Java (Compatibility Mode)
Collections - in - Java (Compatibility Mode)
Collections
● Collection Interface
● Generics
● Implementing classes
Fig:1
Fig:3
Fig:2
Use this class when you want a collection with no duplicates and you do
not care about order when you iterate through it.
Use this class instead of HashSet when you care about the iteration order.
When you iterate through a HashSet the order is unpredictable, while a
LinkedHashSet lets you iterate through the elements in the order in which
they were inserted.
● ArrayList: Think of this as a growable array. It gives you fast iteration and
fast random access. It is an ordered collection (by index).
Choose this over a LinkedList when you need fast iteration but are not as
likely to be doing a lot of insertion and deletion.
● HashMap: The HashMap gives you an unsorted, unordered Map. When you
need a Map and you do not care about the order (when you iterate
through it), then HashMap is the way to go.
The other maps add a little more overhead. Where the keys land in the
Map is based on the key’s hashcode. So, like HashSet, the more efficient
your hashCode() implementation, the better access performance you will
get. HashMap allows one null key and multiple null values in a collection.
Demo:
ArrayListSemo.java
ArrayListDemo.java
Demo:
ItTest.java
ItTest.java
Demo:
ComparatorExample.java
ComparatorExample.java
● Before Generics:
List myIntegerList = new LinkedList(); // 1
myIntegerList.add(new Integer(0)); // 2
Integer x = (Integer) myIntegerList.iterator().next(); // 3
Note: Line no 3 if not properly typecasted will throw runtime exception
● After Generics:
List<Integer> myIntegerList = new LinkedList<Integer>(); // 1
myIntegerList.add(new Integer(0)); //2
Integer x = myIntegerList.iterator().next(); // 3
● Solution: Generics
● Tell the compiler type of the collection.
● Let the compiler fill in the cast.
Example: Compiler will check if you are adding Integer type entry to a
String type collection (compile time detection of type mismatch).
● The enhanced for loop can be used for both Arrays and Collections
CONFIDENTIAL: For limited circulation only Slide 22
Implementing Classes
● ArryaList
● HashSet
● TreeSet
● HashMap
Demo:
ArrayListTest.java
ArrayListDemo.java
Demo:
SetTest.java
SetTest.java
Demo:
TreesetDemo.java
TreesetDemo.java
Demo:
HashMapDemo.java
HashMapDemo.java
Demo:
VectorDemo.java
VectorDemo.java
● Synchronized class
● The Hashtable class only stores objects that override the
hashCode() and equals() methods that are defined by Object.
Demo:
HashTableDemo.java
HashTableDemo.java
● In addition to that, it has got many utility methods for using with
arrays such as a method for viewing arrays as lists and methods for
printing the contents of an array, whatever be the dimension of
the array.
Demo:
ArraysMethodTester.java
ArraysMethodTester.java
Demo:
CollectionsDemo.java
CollectionsDemo.java
● Encapsulate collections.
● Use thread safe collections when needed.