Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Java Collection Framework

This article describes on the working of Java Collection APIs, reason for using Collection Framework and many more.

Collection API, as the name indicates, Collection is simply a container which contains groups of elements and API is Application Programming Interface is a library of functions provided by java for common task such as File transfer, Networking etc.

Thus, Java’s Collections API's provide a set of classes and interfaces within the java.util package that makes it easier to handle collections of objects. Basically, it is a collection of Data Structures which includes ArrayLists, LinkedLists, and HashSets etc. It is used to Store, Retrieve, Manipulate and communicate data of Data Structures.

Why We Use Collection Framework?

  • Arrays are t resizable.
  • Java Collections Framework provides lots of different useful data types, such as linked lists (allows insertion anywhere in constant time), resizable array lists (like Vector but cooler), red-black trees, hash-based maps (like Hashtable but cooler).
  • Java Collections Framework provides abstractions, so you can refer to a list as a List, whether backed by an array list or a linked list; and you can refer to a map/dictionary as a Map, whether backed by a red-black tree or a hashtable.
Features of Collection API: 1 .Allows duplication of data 2. Consist of both Ordered and Unordered Elements

Signature

Public interface <NameOfDataStructure><E>extends Collection<E>
  • Here <E> represents for the type of data.
  • Here NameOfDataStructure represents which type of Data structure we want like Set, List, Queue etc....
  • <E> represents for the type of data like our data structure contain which type of values?

Whether it is a String, Integer or float value it will restrict our data structure to contain only that type value. And since we are using functions which are defied in Collection class of Java for our Data Structure we extend it by Collection class....

Public interface Set<Integer> extends Collection< Integer >

There are two constructors provided by all the general-purpose Collection implementation classes. These classes typically implement Collection indirectly through one of its sub interfaces.

  1. Void (no arguments) constructor which creates an empty collection.
  2. Constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Collection Interface Hierarchy:

Java Collection Framework - Set Interface

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

The set interface extends the Collection interface and, by definition, forbids duplicates within the collection. All the original methods are present and no new method is introduced. The concrete Set implementation classes rely on the equals() method of the object added to check for equality.

Methods Uses
Boolean add (Object o) Ensures that this collection contains the specified element

Boolean addAll

(Collection c)
Adds all of the elements in the specified collection to this collection
Void clear() Removes all of the elements from this collection

Boolean contains

(Object o)
Returns true if this collection contains the specified element.
Boolean containsAll(Collection c) Returns true if this collection contains all of the elements in the specified collection.

int hashCode()

Returns the hash code value for this collection.

Boolean isEmpty()

Returns true if this collection contains no elements.

Boolean remove (Object o) Removes a single instance of the specified element from this collection, if it is present
removeAll(Collection c) Removes all this collection's elements that are also contained in the specified collection
Boolean retainAll(Collection c) Retains only the elements in this collection that are contained in the specified collection
Int size() Returns the number of elements in this collection.
Object[] toArray()

Returns an array containing all of the elements in this collection.

Object[] toArray(Object[]

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

Listing 1: Java Collection Framework Set Interface Example

import java.util.*;
public class SetDemo
 {
    public static void main(String args[])
    { 
       int age[] = {15,8,3,16,25,5};
      //A  HashSet is a collection set that neither allows  duplicate elements nor order or    position its elements
     Set<Integer> set = new HashSet<Integer>();  
     try
     {
        for(int i = 0; i<5; i++){
           set.add(age[i]);
      }
     System.out.println(set);
  
    TreeSet sortedSet = new TreeSet<Integer>(set);
    System.out.println("The sorted list is:");
    System.out.println(sortedSet);

    System.out.println("The First element of the set is: "+
                          (Integer)sortedSet.first());
   System.out.println("The last element of the set is: "+
         (Integer)sortedSet.last());
     }
     catch(Exception e){}
  }
}

This would produce following result:

[15, 8, 3, 16, 25, 5]
The sorted list is:
[3, 5, 8, 15, 16, 25]
The First element of the set is: 3
The last element of the set is: 25

Java Collection Framework - List Interface

The List interface extends Collection and stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements.

Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

Methods Uses
void add(int index, Object obj) Inserts obj into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.

Boolean addAll

(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.
Object get(int index) Returns the object stored at the specified index within the invoking collection.
int indexOf(Object obj) Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
int lastIndexOf(Object obj) Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
ListIterator listIterator( ) Returns an Iterator to the start of the invoking list
ListIterator listIterator(int index) Returns an Iterator to the invoking list that begins at the specified index.
Object remove(int index) Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted.
Object set(int index, Object obj) Assigns obj to the location specified by index within the invoking list.
List subList(int start, int end) Returns a list that includes elements from start to end.1 in the invoking list.

Listing 2: Java Collection Framework List Interface Example

import java.util.*;
Public class ListDemo
 {
    Public static void main(String[] args)
    {
    List a = new ArrayLists ();
     a. add("a");
     a. add("b");
     a. add ("c");
     System.out.println (" Array List Elements");
     System.out.println ("\t" + a);

     List l = new LinkedList ();
     l.add ("x");
     l.add ("y");
     l.add ("z");
     System.out.println ();
     System.out.println (" LinkedList Elements");
     System.out.println ("\t" + l);
   }
}

This would produce following result:

ArrayLists Elements
[a, b, c]
LinkedList Elements
[x, y, z]

Java Collection Framework - Queue Interface

Methods Uses
get() Returns the element at the specified index position in this collection
listIterator() Returns a List Iterator object for the collection which may then be used to retrieve an object
Remove() Removes the element at the specified index position in this collection.
Peek() Returns an element but if queue is empty then it returns null.
Poll() Removes an element but returns null if the queue is empty.

Listing 3: Java Collection Framework Queue Interface Example

import java.util.LinkedList;
import java.util.Queue;
public class ListQueueDemo {

    public void queueExample() {

        Queue<String> queue = new LinkedList<String>();

        queue.add("Java");
        queue.add("DotNet");

        queue.offer("PHP");
        queue.offer("HTML");

        System.out.println("remove: " + queue.remove());
        System.out.println("element: " + queue.element());
        System.out.println("poll: " + queue.poll());
        System.out.println("peek: " + queue.peek());

    }

    public static void main(String[] args) {
        new ListQueueDemo().queueExample();
    }
}

This would produce following result:

ListQueueDemo

The List is:
[16, 3, 25, 8, 15]

The Sorted list is:
[3, 8, 15, 16, 25]

The First Element of the set is: 3

The Last Element of the set is: 25

Java Collection Framework - SortedList Interface

Last Collection interface is SortedList it is same as List Interface but the only difference is that it allows data only in sorted order.

Conclusion

Collection API has made easier to resize the array that was previous not possible. It is a collection of Data Structures. Collection Framework powerful set of well engineered solution that gives benefits to programmers to programming’s most common task. It’s a reusable API we supports functionality to store and retrieve information.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login