Download link:

Java Collections Framework

A collection sometimes called a container is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

A collection is the same as the intuitive, mathematical concept of a set. A set is just a group of unique items, meaning that the group contains no duplicates. Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. The framework provides a convenient API to many of the abstract data types maps, sets, lists, trees, arrays, hashtables, and other collections. Because of their object-oriented design, the Java classes in the Collections Framework encapsulate both the data structures and the algorithms associated with these abstractions. With the Java Collections Framework the programmer easily define higher level dataabstractions, such as stacks, queues, and thread safe collections.

You should be able to understand the Collections Framework more easily. The Collections Framework is made up of a set of interfaces for working with groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. The following diagrams shows the framework interface hierarchy.

What Is a Collections Framework?

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

  • Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
  • Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
  • Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

Benefits of the Java Collections Framework

The Java Collections Framework provides the following benefits:

  1. Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.
  2. Increases program speed and quality:The Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.
  3. Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, APIs will interoperate seamlessly, even though they were written independently.
  4. Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.
  5. Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.
  6. Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

The Java Collections Framework consists of following classes, interfaces and utility classes.

  • Collection Classes

AbstractCollection

AbstractList

AbstractMap

AbstractQueue

AbstractSequentialList

AbstractSet

ArrayDeque

ArrayList

Arrays

Collections

EnumMap

EnumSet

HashMap

HashSet

Hashtable

IdentityHashMap

LinkedHashMap

LinkedHashSet

LinkedList

PriorityQueue

TreeMap

TreeSet

Vector

WeakHashMap

  • Collection Interfaces

Collection

Set

List

Queue

Deque

Map

SortedSet

SortedMap

NavigableSet

NavigableMap

BlockingQueue

BlockingDeque

ConcurrentMap

ConcurrentNavigableMap

java.util.Arrays Class

This class contains various methods for manipulating arrays (such as sorting and searching). This class contains a static factory that allows arrays to be viewed as lists. You need not to instantiate java.util.Arrays class because all the methods are static methods so that we can call the methods with the class name.

The methods in this class all throw a NullPointerException if the specified array reference is null, except where noted.

In this tutorial you can learn about java.util.Arrays class and its examples. And also learn how to use java.util.Arrays class.

Following example shows how to use int array with java.util.Arrays class.

/* java.util.Arrays class Example */

/* Save with file name ArraysExample.java */

import java.util.Arrays;

public class ArraysExample

{

public static void main(String args[])

{

//int ARRAY DECLARATION AND CREATION

int arr[] = {0,-5,2,5,-1,-4,-3,-2,3,1,4};

//int ARRAY OUTPUT AS STRING

System.out.println(Arrays.toString(arr));

//int ARRAY SORTING

Arrays.sort(arr);

//int ARRAY OUTPUT AS STRING AFTER SORTING

System.out.println("After Sorting");

System.out.println(Arrays.toString(arr));

//SEARCHING IN int ARRAY

int index = Arrays.binarySearch(arr, 3);

if( index >= 0 )

System.out.println("3 is Found at Index : " + index);

else

System.out.println("3 is NOT Found");

//FILLING int ARRAY WITH DEFAULT ZERO

Arrays.fill(arr,0);

//int ARRAY OUTPUT AFTER FILL

System.out.println(Arrays.toString(arr));

}

}

Following example shows how to use double array with java.util.Arrays class.

/* java.util.Arrays class Example 2 */

/* Save with file name ArraysExample2.java */

import java.util.Arrays;

public class ArraysExample2

{

public static void main(String args[])

{

//double ARRAY DECLARATION AND CREATION

double arr[] = {0.0,-5.0,2.0,5.0,-1.5,-4.0,-3.0,-2.0,3.0,1.5,4.0};

//double ARRAY OUTPUT AS STRING

System.out.println(Arrays.toString(arr));

//double ARRAY SORTING

Arrays.sort(arr);

//double ARRAY OUTPUT AS STRING AFTER SORTING

System.out.println("After Sorting");

System.out.println(Arrays.toString(arr));

//SEARCHING IN double ARRAY

int index = Arrays.binarySearch(arr, 3);

if( index >= 0 )

System.out.println("3 is Found at Index : " + index);

else

System.out.println("3 is NOT Found");

//FILLING double ARRAY WITH DEFAULT ZERO

Arrays.fill(arr,0);

//double ARRAY OUTPUT AFTER FILL

System.out.println(Arrays.toString(arr));

}

}

Note: When filling an object array, the fill() method will copy the same object reference to every cell in the array. After filling the array, if you then change that one reference, the attributes of the object in every cell in the array will be changed.

Following example shows how to use String array with java.util.Arrays class.

/* java.util.Arrays class Example 3 */

/* Save with file name ArraysExample3.java */

import java.util.Arrays;

import java.util.Collections;

public class ArraysExample3

{

public static void main(String args[])

{

//String ARRAY DECLARATION AND CREATION

String arr[] = {"Java Tutorials","NetBeans Tutorials","Huda Tutorials","C"};

//String ARRAY OUTPUT AS STRING

for(int i=0; i < arr.length; i++)

{

System.out.println(arr[i]);

}

//String ARRAY SORTING

Arrays.sort(arr);

//String ARRAY OUTPUT AS STRING AFTER SORTING

System.out.println("\nAfter Sorting\n");

for(int i=0; i < arr.length; i++)

{

System.out.println(arr[i]);

}

//SEARCHING IN String ARRAY

int index = Arrays.binarySearch(arr, "Huda Tutorials");

if( index >= 0 )

System.out.println("\nHuda Tutorials is Found at Index : " + index);

else

System.out.println("\nHuda Tutorials is NOT Found");

//String ARRAY REVERSE ORDER

Arrays.sort(arr,Collections.reverseOrder());

//String ARRAY OUTPUT AS STRING AFTER SORTING

System.out.println("\nAfter Reverse Order\n");

for(int i=0; i < arr.length; i++)

{

System.out.println(arr[i]);

}

//FILLING String ARRAY WITH DEFAULT null

Arrays.fill(arr,null);

//String ARRAY OUTPUT AFTER FILL

System.out.println(Arrays.toString(arr));

}

}

java.util.ArrayList Class

The ArrayList class is the Collection Framework's replacement for the Vector class. Functionally equivalent, their primary difference is that ArrayList usage is not synchronized by default, whereas Vector is. Both maintain their collection of data in an ordered fashion within an array as their backing store.

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

The array provides quick, random access to elements at a cost of slower insertion and deletion of those elements not at the end of the list. If you need to frequently add and delete elements from the middle of the list, consider using a LinkedList.

ArrayList shares some similarities with HashSet and TreeSet and provides some behavior that is not the same. The base implementation class is similar to HashSet and TreeSet both extend from the AbstractCollection superclass. However, instead of further extending from AbstractSet, ArrayList extends from AbstractList. Unlike the sets, ArrayList supports storing duplicate elements. While much of the ArrayList behavior is inherited from AbstractList, the class still needs to customize the majority of its behavior.

ArrayList class has following constructors.

ArrayList()

Constructs an empty list with an initial capacity of ten.

ArrayList(Collection<? extends E> c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

ArrayList(int initialCapacity)

Constructs an empty list with the specified initial capacity.

In this tutorial you can learn about java.util.ArrayList class and its examples. And also learn how to use java.util.ArrayList class.

/* java.util.ArrayList class Example */

/* Save with file name ArrayListExample.java */

import java.util.ArrayList;

public class ArrayListExample

{

public static void main(String args[])

{

//java.util.ArrayList DECLARATION

ArrayList al;

//java.util.ArrayList OBJECT CREATION

//USING DEFAULT CONSTRUCTOR

al = new ArrayList();

//ADD AN ELEMENT

al.add("Huda Tutorials");

al.add("Java Tutorials");

//DUPLICATES ARE ALLOWED

al.add("Huda Tutorials");

al.add("C Tutorials");

al.add("CPP Tutorials");

//null ALLOWED

al.add(null);

//RETURNS COUNT OF ELEMENTS ArrayList CONTAINS

System.out.println("Elements Count : " + al.size());

//java.util.ArrayList OUTPUT

System.out.println(al);

}

}

The following example shows how to use ArrayList with Iterator.

/* java.util.ArrayList class Example 2 */

/* Save with file name ArrayListExample2.java */

import java.util.ArrayList;

import java.util.Iterator;

public class ArrayListExample2

{

public static void main(String args[])

{

//java.util.ArrayList DECLARATION

ArrayList al;

//java.util.ArrayList OBJECT CREATION

//USING DEFAULT CONSTRUCTOR

al = new ArrayList();

//ADD AN ELEMENT

al.add("Huda Tutorials");

al.add("Java Tutorials");

//DUPLICATES ARE ALLOWED

al.add("Huda Tutorials");

al.add("C Tutorials");

al.add("CPP Tutorials");

//null ALLOWED

al.add(null);

//RETURNS COUNT OF ELEMENTS ArrayList CONTAINS

System.out.println("Elements Count : " + al.size());

//java.util.ArrayList OUTPUT

Iterator itr = al.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

}

}

The following example shows how to use ArrayList with Arrays, List and Iterator.

/* java.util.ArrayList class Example 3 */

/* Save with file name ArrayListExample3.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

public class ArrayListExample3

{

public static void main(String args[])

{

String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

List s; //java.util.List DECLARATION

//java.util.List OBJECT CREATION USING ARRAY AS LIST

s = new ArrayList(Arrays.asList(elements));

//java.util.List OUTPUT

Iterator itr = s.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

}

}

/* java.util.ArrayList class Example 4 */

/* Save with file name ArrayListExample4.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

public class ArrayListExample4

{

public static void main(String args[])

{

String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

List s; //java.util.List DECLARATION

//java.util.List OBJECT CREATION USING ARRAY AS LIST

s = new ArrayList(Arrays.asList(elements));

//ADD ELEMENT TO List COLLECTION

s.add("NetBeans Tutorials");

//DISPLAY SIZE OF THE List COLLECTION

System.out.println("List Collection Size : "+s.size());

//CHECK THE List COLLECTION IS EMPTY

System.out.println("List Collection is Empty : "+s.isEmpty());

//CHECK THE GIVEN ELEMENT IN List COLLECTION

System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials"));

//java.util.List OUTPUT

System.out.println();

System.out.println("Elements Before Element Remove");

System.out.println("------");

Iterator itr = s.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

s.remove("C Tutorials");

System.out.println();

System.out.println("Elements After Element Remove");

System.out.println("------");

itr = s.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

}

}

The following example shows how to compare two List Collections.

/* java.util.ArrayList class Example 5 */

/* Save with file name ArrayListExample5.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;

public class ArrayListExample5

{

public static void main(String args[])

{

String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

//java.util.List DECLARATION

List s, s2;

//java.util.List OBJECT CREATION USING ARRAY AS LIST

s = new ArrayList(Arrays.asList(elements));

s2 = new ArrayList(Arrays.asList(elements2));

//COMPARE TWO COLLECTIONS

System.out.println("Equals : " + s2.equals(s));

//CONTAINS COLLECTION IN OTHER COLLECTION

System.out.println("Contains : " + s2.containsAll(s));

}

}

The following example shows how to save List Collection into file.

/* java.util.ArrayList class Example 6 */

/* Save with file name ArrayListExample6.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;

public class ArrayListExample6

{

public static void main(String args[])

{

try

{

String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};

//java.util.ArrayList DECLARATION

List s;

//java.util.List OBJECT CREATION USING ARRAY AS LIST

s = new ArrayList(Arrays.asList(elements));

//FileOutputStream CREATION

FileOutputStream fos = new FileOutputStream("List.set");

//ObjectOutputStream CREATION

ObjectOutputStream oos = new ObjectOutputStream(fos);

//WRITE List OBJECT TO ObjectOutputStream

oos.writeObject(s);

//CLOSE THE ObjectOutputStream

oos.close();

System.out.println("List Collection Saved into File Sucessfully");

}

catch(Exception e)

{

System.out.println("Error Occurred : " + e.getMessage());

}

}

}

The following example shows how to retrieve List Collection from file.

/* java.util.ArrayList class Example 7 */

/* Save with file name ArrayListExample7.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

public class ArrayListExample7

{

public static void main(String args[])

{

try

{

//java.util.ArrayList DECLARATION

List s;

//FileInputStream CREATION

FileInputStream fis = new FileInputStream("List.set");

//ObjectInputStream CREATION

ObjectInputStream ois = new ObjectInputStream(fis);

//READ List OBJECT FROM ObjectInputStream

s = (List) ois.readObject();

ois.close();

System.out.println(s);

}

catch(Exception e)

{

System.out.println("Error Occurred : " + e.getMessage());

}

}

}

The following example shows how to use ArrayList with Arrays, List and ListIterator.

/* java.util.ArrayList class Example 8 */

/* Save with file name ArrayListExample8.java */

import java.util.ArrayList;

import java.util.List;

import java.util.Arrays;

import java.util.ListIterator;

public class ArrayListExample8

{

public static void main(String args[])

{

String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};

List s; //java.util.List DECLARATION

//java.util.List OBJECT CREATION USING ARRAY AS LIST

s = new ArrayList(Arrays.asList(elements));