A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections. Collection is a Java Interface. Collections can be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically used to group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Some collections are ordered and others are not.
A Collections Framework mainly contains the following 3 parts
A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides severalabstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.Core Collection Interfaces
The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation.The 6 core Interfaces used in the Collection framework are:
- Collection
- Set
- List
- Iterator (Not a part of the Collections Framework)
- SortedSet
- Map
- SortedMap
Collection Interface
Map Interface Concrete ClassesThe concrete classes that are specific implementations of the core interfaces, providing data structures that a java program can use. Note: Concrete Classes for the Map is shown in the previous section. |
Standard utility methods and algorithms
that can be used to perform various operations on collections, such as sorting, searching or creating customizedcollections.
How are Collections Used
- The collections stores object references, rather than objects themselves. Hence primitive values cannot be stored in a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior tostoring them into a Collection (such as HashSet, HashMap etc).
- The references are always stored as type Object. Thus, when you retrieve an element from a collection, you get an Object rather then the actual type of the collection stored in the database. Hence we need to downcast it to the Actual Type while retrieving an element from a collection.
- One of the capabilities of the Collection Framework is to create a new Collection object and populate it with the contents of an existing Collection object of a same or different actual type.
Below is an example program showing the storing and retrieving of a few Collection Types
import java.util.*; public class CollectionsDemo { public static void main(String[] args) { List a1 = new ArrayList(); a1.add("Beginner"); a1.add("Java"); a1.add("tutorial"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Beginner"); l1.add("Java"); l1.add("tutorial"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); Set s1 = new HashSet(); // or new TreeSet() will order the elements; s1.add("Beginner"); s1.add("Java"); s1.add("Java"); s1.add("tutorial"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); Map m1 = new HashMap(); // or new TreeMap() will order based on keys m1.put("Windows", "98"); m1.put("Win", "XP"); m1.put("Beginner", "Java"); m1.put("Tutorial", "Site"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } } |
Output
ArrayList Elements[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}
Java ArrayList
public class ArrayList<E>extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
- Resizable-array implementation of the List interface. A java ArrayList is used to store an “ordered” group of elements where duplicates are allowed.
- Implements all optional list operations, and permits all elements, including null.
- This class is similar to Vector, except that it is unsynchronized.
- The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayList’s give great performance on get() and set() methods, but do not perform well on add() and remove() methods when compared to a LinkedList.
- An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to anArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can be accessed directly through get() method.
Below is an ArrayList Example showing how collections are manipulated using an ArrayList
import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.Collections; import java.util.Random; public class ArrayListExample { public static void main(String[] args) { // ArrayList Creation List arraylistA = new ArrayList(); List arraylistB = new ArrayList(); // Adding elements to the ArrayList for (int i = 0; i < 5; i++) { arraylistA.add(new Integer(i)); } arraylistB.add("beginner"); arraylistB.add("java"); arraylistB.add("tutorial"); arraylistB.add("."); arraylistB.add("com"); arraylistB.add("java"); arraylistB.add("site"); // Iterating through the ArrayList to display the Contents. Iterator i1 = arraylistA.iterator(); System.out.print("ArrayList arraylistA --> "); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.print("ArrayList arraylistA --> "); for (int j = 0; j < arraylistA.size(); j++) { System.out.print(arraylistA.get(j) + " , "); } System.out.println(); Iterator i2 = arraylistB.iterator(); System.out.println("ArrayList arraylistB --> "); while (i2.hasNext()) { System.out.print(i2.next() + " , "); } System.out.println(); System.out.println(); System.out .println("Using ListIterator to retrieve ArrayList Elements"); System.out.println(); ListIterator li1 = arraylistA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("ArrayList arraylistA --> "); while (li1.hasNext()) { System.out.print(li1.next() + " , "); } System.out.println(); // Searching for an element in the ArrayList int index = arraylistB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = arraylistB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex + " from the last"); System.out.println(); // Getting the subList from the original List List subList = arraylistA.subList(3, arraylistA.size()); System.out.println("New Sub-List(arraylistA) from index 3 to " + arraylistA.size() + ": " + subList); System.out.println(); // Sort an ArrayList System.out.print("Sorted ArrayList arraylistA --> "); Collections.sort(arraylistA); System.out.print(arraylistA); System.out.println(); // Reversing an ArrayList System.out.print("Reversed ArrayList arraylistA --> "); Collections.reverse(arraylistA); System.out.println(arraylistA); System.out.println(); // Checking emptyness of an ArrayList System.out.println("Is arraylistA empty? " + arraylistA.isEmpty()); System.out.println(); // Checking for Equality of ArrayLists ArrayList arraylistC = new ArrayList(arraylistA); System.out.println("arraylistA.equals(arraylistC)? " + arraylistA.equals(arraylistC)); System.out.println(); // Shuffling the elements of an ArrayList in Random Order Collections.shuffle(arraylistA, new Random()); System.out .print("ArrayList arraylistA after shuffling its elements--> "); i1 = arraylistA.iterator(); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.println(); // Converting an ArrayList to an Array Object[] array = arraylistA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing ArrayList Elements arraylistA.clear(); System.out.println("arraylistA after clearing : " + arraylistA); System.out.println(); } } |
Output
ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,ArrayList arraylistA –> 0 , 1 , 2 , 3 , 4 ,
ArrayList arraylistB –>
beginner , java , tutorial , . , com , java , site ,
Using ListIterator to retrieve ArrayList Elements
ArrayList arraylistA –>
0 , 1 , 2 , 3 , 4 ,
‘java’ was found at : 1
‘java’ was found at : 5 from the last
New Sub-List(arraylistA) from index 3 to 5: [3, 4]
Sorted ArrayList arraylistA –> [0, 1, 2, 3, 4]
Reversed ArrayList arraylistA –> [4, 3, 2, 1, 0]
Is arraylistA empty? false
arraylistA.equals(arraylistC)? true
ArrayList arraylistA after shuffling its elements–> 3 , 2 , 1 , 0 , 4 ,
Array Element [0] = 3
Array Element [1] = 2
Array Element [2] = 1
Array Element [3] = 0
Array Element [4] = 4
arraylistA after clearing : []
JavaLinked List
- A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.
- A LinkedList is based on a double linked list where elements of the List are typically accessed throughadd() and remove() methods.
Below is an LinkedList Example showing how collections are manipulated using an LinkedList
import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.ListIterator; import java.util.Collections; import java.util.Random; public class LinkedListExample { public static void main(String[] args) { // LinkedList Creation List linkedListA = new LinkedList(); List linkedListB = new LinkedList(); // Adding elements to the LinkedList for (int i = 0; i < 5; i++) { linkedListA.add(new Integer(i)); } linkedListB.add("beginner"); linkedListB.add("java"); linkedListB.add("tutorial"); linkedListB.add("."); linkedListB.add("com"); linkedListB.add("java"); linkedListB.add("site"); // Iterating through the LinkedList to display the Contents. Iterator i1 = linkedListA.iterator(); System.out.print("LinkedList linkedListA --> "); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.print("LinkedList linkedListA --> "); for (int j = 0; j < linkedListA.size(); j++) { System.out.print(linkedListA.get(j) + " , "); } System.out.println(); Iterator i2 = linkedListB.iterator(); System.out.println("LinkedList linkedListB --> "); while (i2.hasNext()) { System.out.print(i2.next() + " , "); } System.out.println(); System.out.println(); System.out .println("Using ListIterator to retrieve LinkedList Elements"); System.out.println(); ListIterator li1 = linkedListA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("LinkedList linkedListA --> "); while (li1.hasNext()) { System.out.print(li1.next() + " , "); } System.out.println(); // Searching for an element in the LinkedList int index = linkedListB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = linkedListB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex + " from the last"); System.out.println(); // Getting the subList from the original List List subList = linkedListA.subList(3, linkedListA.size()); System.out.println("New Sub-List(linkedListA) from index 3 to " + linkedListA.size() + ": " + subList); System.out.println(); // Sort an LinkedList System.out.print("Sorted LinkedList linkedListA --> "); Collections.sort(linkedListA); System.out.print(linkedListA); System.out.println(); // Reversing an LinkedList System.out.print("Reversed LinkedList linkedListA --> "); Collections.reverse(linkedListA); System.out.println(linkedListA); System.out.println(); // Checking emptyness of an LinkedList System.out.println("Is linkedListA empty? " + linkedListA.isEmpty()); System.out.println(); // Checking for Equality of LinkedLists LinkedList LinkedListC = new LinkedList(linkedListA); System.out.println("linkedListA.equals(LinkedListC)? " + linkedListA.equals(LinkedListC)); System.out.println(); // Shuffling the elements of an LinkedList in Random Order Collections.shuffle(linkedListA, new Random()); System.out .print("LinkedList linkedListA after shuffling its elements--> "); i1 = linkedListA.iterator(); while (i1.hasNext()) { System.out.print(i1.next() + " , "); } System.out.println(); System.out.println(); // Converting an LinkedList to an Array Object[] array = linkedListA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing LinkedList Elements linkedListA.clear(); System.out.println("linkedListA after clearing : " + linkedListA); System.out.println(); } } |
Output
LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,LinkedList linkedListA –> 0 , 1 , 2 , 3 , 4 ,
LinkedList linkedListB –>
beginner , java , tutorial , . , com , java , site ,
Using ListIterator to retrieve LinkedList Elements
LinkedList linkedListA –>
0 , 1 , 2 , 3 , 4 ,
‘java’ was found at : 1
‘java’ was found at : 5 from the last
New Sub-List(linkedListA) from index 3 to 5: [3, 4]
Sorted LinkedList linkedListA –> [0, 1, 2, 3, 4]
Reversed LinkedList linkedListA –> [4, 3, 2, 1, 0]
Is linkedListA empty? false
linkedListA.equals(LinkedListC)? true
LinkedList linkedListA after shuffling its elements–> 3 , 2 , 4 , 0 , 1 ,
Array Element [0] = 3
Array Element [1] = 2
Array Element [2] = 4
Array Element [3] = 0
Array Element [4] = 1
linkedListA after clearing : []
Java TreeSet
extends AbstractSet<E>
implements SortedSet<E>, Cloneable, Serializable
- This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used.
- This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Below is a TreeSet Example showing how collections are manipulated using a TreeSet
import java.util.Set; import java.util.TreeSet; import java.util.Iterator; public class TreeSetExample { public static void doTreeSetExample() { } public static void main(String[] args) { Set treeSet = new TreeSet(); // the treeset stores Integer objects into the TreeSet for (int i = 0; i < 5; i++) { treeSet.add(new Integer(i)); } // Since its a Integer Object Set adding any other elements in the Same // set will produce a // ClassCastException exception at runtime. // treeSet.add("a string"); System.out.print("The elements of the TreeSet are : "); Iterator i = treeSet.iterator(); while (i.hasNext()) { System.out.print(i.next() + "\t"); } } } |
Output
The elements of the TreeSet are : 0 1 2 3 4Java HashMap
- The java HashMap class does not guarantee that the order will remain constant over time.
- This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
- The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
Below is a HashMap Example used to store the number of words that begin with a given letter
/* * Using a HashMap to store the number of words that begin with a given letter. */ import java.util.HashMap; public class HashMapExample { static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" }; private static HashMap counter = new HashMap(); private static Integer cnt = null; public static void main(String args[]) { for (int i = 0; i < names.length; i++) { cnt = (Integer) (counter.get(new Character(names[i].charAt(0)))); if (cnt == null) { counter.put(new Character(names[i].charAt(0)),new Integer("1")); } else { counter.put(new Character(names[i].charAt(0)), new Integer(cnt.intValue() + 1)); } } System.out.println("\nnumber of words beginning with each letter is shown below "); System.out.println(counter.toString()); } } |
number of words beginning with each letter is shown below
{s=3, b=1, k=1, h=2}
Java Vector
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
- The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically.
- Like an array, it contains components that can be accessed using an integer index.
- An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Below is a Vector Example showing how collections are manipulated using a Vector
import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class VectorDemo extends JFrame { private JLabel jlbString = new JLabel("Enter a string"); public VectorDemo() { super("Vector class demo"); // Made final as it can be accessed by inner classes final JLabel jlbStatus = new JLabel(); |
Java HashTable
- HashTable is synchronized.
- Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
- Hashtable doesn’t allow nulls
Below is a HashTable Example showing how collections are manipulated using a HashTable
Please Note that It must be Compiled in Java 1.4.
// Demonstrates the Hashtable class of the java.util package. public class HashTableDemo extends JFrame { public HashTableDemo() { super(" Hashtable Sourcecode Example"); final JLabel jlbStatus = new JLabel(); final Hashtable hashTable = new Hashtable(); final JTextArea display = new JTextArea(4, 20); display.setEditable(false); JPanel jplNorth = new JPanel(); jplNorth.setLayout(new BorderLayout()); JPanel jplNorthSub = new JPanel(); jplNorthSub.add(new JLabel("Name (Key)")); final JTextField jtfFirstName = new JTextField(8); jplNorthSub.add(jtfFirstName); jplNorthSub.add(new JLabel("Phone No")); final JTextField jtfPhone = new JTextField(8); jplNorthSub.add(jtfPhone); jplNorth.add(jplNorthSub, BorderLayout.NORTH); jplNorth.add(jlbStatus, BorderLayout.SOUTH); JPanel jplSouth = new JPanel(); jplSouth.setLayout(new GridLayout(2, 5)); JButton jbnAdd = new JButton("Add"); |
Output
Java HashSet
- The HashSet class implements the Set interface.
- It makes no guarantee that the order of elements will remain constant over time.
- This class is not synchronized and permits a null element.
- This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
- To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet(…));
Below is a HashSet Example showing how collections are manipulated using a HashSet
import java.util.*; public class HashSetExample { private static String names[] = { "bob", "hemanth", "hhh", "hero", "shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike", "undertaker" }; public static void main(String args[]) { ArrayList aList; aList = new ArrayList(Arrays.asList(names)); System.out.println("The names elements " + aList); HashSet ref = new HashSet(aList); // create a HashSet Iterator i = ref.iterator(); System.out.println(); System.out.print("Unique names are: "); while (i.hasNext()) System.out.print(i.next() + " "); System.out.println(); } } |
The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker]Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker