Reading:  

Quick walk through the advanced concepts in Java - Part 3 of series


Working with Collections

Collection in Java is a frameworkrepresents a unit of objectswhich gives architecture to store and manipulate the objects.All the tasks we perform on a data likeinsertion, searching, manipulation sorting, deletion etc. can be performed by Java collection and extending and/or adapting a collection had to be easy. 

Framework which provides:

  • It gives an instant architecture
  • It represents group of interface and classes 

 

Hierarchy of collection Framework:

 

 

Collection Interfaces:

  • List
  • Set
  • Queue
  • Map 

 Collection Classes:

  • Vector and Stack
  • LinkedList and ArrayList
  • HashSet and TreeSet
  • ArrayList andLinkedList
  • HashMap andTreemap

The interfaces and classes of the collections are available in java.utilpackage.

 

Methods of Collection Interface:

  • int size(): Which returns total number of elements
  • boolean isempty(): verifies if collection is empty
  • object[] toArray():to convert a collection into array
  • boolean remove(object obj):which delete an element if element is present
  • boolean containsAll(object obj):to find specified elements in specified collection
  • void clear(): removes entire elements from collection
  • boolean add(object obj):to add an element
  • boolean removeAll(collection col): removes entire this collection of elements that contained in specified collection.
  • boolean addAll(collection col):to add specified collection of element to a specified collection.
  • boolean contains(object ele):to find an element
  • Iterator iterator(): returns an iterator
  • boolean equals(object ele): to compare specified object with collection
  • boolean retainAll(collection col): retains element that are contained in specified collection
  • int hashcode():returns hash code value for collection

 

List:

  • List is an index based
  • List accepts duplicate and null values
  • List maintains the insertion order

ArrayList:

  • ArrayList uses resizable arrays to store elements
  • Methods are not synchronized; hence it is not thread safe.

 

Example for List:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListExample {

	public static void main(String[] args) {
		List l1 = newArrayList();
		l1.add(10);
		l1.add(40);
		l1.add(5);
		System.out.println("The ArrayList contains:");
		System.out.print(l1);

		List s1 = newLinkedList();
		s1.add("Java");
		s1.add("Collection");
		s1.add("LinkedList");
		System.out.println("\n" + "TheLinkedList contains:");
		System.out.print(s1);
	}
}

 

The Output is:

 

Note: Refer Java Data Structures for Vector and Stack.

 

Set:

  • Set is a group of unique elements.
  • It is not index based

HashSet:

  • HashSet uses hashing technique to store elements
  • In hashSet insertion order is not preserved
  • In Linked hashSet insertion order is preserved

TreeSet:

  • TreeSet stores elements in sorting order
  • It contains only unique values

 

Example for Set:

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;


public class SetExample {

	public static void main(String[] args) {@SuppressWarnings("rawtypes")
		Set s1 = new HashSet();
		s1.add(10);
		s1.add(30);
		s1.add(2);
		System.out.println("The HashSet contains:");
		System.out.println(s1);

		Set h1 = new LinkedHashSet();
		h1.add(10);
		h1.add(40);
		h1.add(9);
		System.out.println("The linkedhashSet contains:");
		System.out.println(h1);

		Set t1 = new TreeSet();
		t1.add(20);
		t1.add(11);
		t1.add(38);
		System.out.println("The TreeSet contains:");
		System.out.println(t1);

	}
}

Output

 

Queue:

  • Queue is not an index based
  • Queue is first in first out (FIFO)
  • Queue cannot take null values
  • Queue can have duplicate values 

Priority Queue:

  • Priorityqueue can store only elements of type comparable
  • When we add elements into priority queue, elements are sorted according to priorities
  • Insertion order is not preserved

 

Example for Queue:

importjava.util.LinkedList;
importjava.util.PriorityQueue;
importjava.util.Queue;


public class QueueExample {

	publicstaticvoid main(String args[]) {
	Queue q = newLinkedList();
	q.add(10);
	q.add(1);
	q.add(5);
	q.add(6);
	System.out.println("LinkedList queue: "+q.peek());  //returns head element
	System.out.println("LinkedList queue: "+q.poll());  //removes head element and returns the removed element
	System.out.println("LinkedList queue: "+q.size());  //returns size of queue
	System.out.println(q);
	
	Queue pq = new PriorityQueue();
	pq.add(20);
	pq.add(11);
	pq.add(7);
	pq.add(2);
	System.out.println("Priority Queue: "+pq.peek());
	System.out.println("Priority Queue: "+pq.poll());
	System.out.println("Priority Queue: "+pq.size());
	System.out.println(pq);
	
	}
}
 

Output

 

Map:

  • Map stores key-value pair
  • Keys should be unique

 

Example for Map:

import java.util.HashMap;

public class MapExample {

	public static void main(String args[]) {
		HashMap m = new HashMap();
		m.put("Physics", 97); //to add value
		m.put("Java", 86); //to add value
		m.put("Chemistry", 81); //to add value
		System.out.println("The HashMap contains: ");
		System.out.println(m);
		System.out.println("Java = " + m.get("Java")); //to get value at a particular key

	}
}


Output

Iterator Interface: facilitates to iterate the elements in forward direction.

Methods of iterator:

  • void remove(): removes the element which is in last position, is used to remove current element in collection
  • booleanhasNext(): returns true if iterator has elements, is used to check next element is exist or not
  • Object next(): returns the element and cursor points to next element, is used to read the next element in collection object

 

Example for Iterator:

import java.util.ArrayList;
import java.util.Iterator;


public class IteratorExample {

	public static void main(String args[]) {
		ArrayList a = new ArrayList();
		a.add(10);
		a.add(13);
		a.add(1);
		a.add(3);
		Iterator i = a.iterator();
		System.out.println("The ArrayListusing iterator: ");
		while (i.hasNext()) {
			System.out.println(i.next());
		}
	}
}

Output


To use Comparator:

There are two methods:

  • compareTo( ):comparing two objects objectA and object if objects are matched returns zero. ifobjectA is greater than object returns a positive value or else return a negative value.
  • equals( ): this method compares current instance/object(not the value given) with given instance, returns true if both are same or else return false.

 

Example for comapareTo():

public class CompareExample {

	public static void main(String args[]) {
		String str1 = "Java";
		String str2 = "Java";
		String str3 = "compare";
		System.out.println("Comparing Matched values: " + str1.compareTo(str2));
		System.out.println("Comparing Unmatched values: " + str1.compareTo(str3));
	}
}

Output

Example for equals():

public class Tree {

	int height;
	Tree(int height) {
		this.height = height;
	}

	public static void main(String[] args) {
		Tree t1 = new Tree(21);
		Tree t2 = new Tree(8);
		System.out.println("Comparing different objects using equals(): " + t1.equals(t2)); //equals() compares instance not the values hence returns false

		System.out.println("Comparing same object equals(): " + t1.equals(t1)); // comparing same object hence return true.

	}
}

 Output

Description

This is the last part in our tutorial series on Java. This tutorial is designed as a quick walk through the advanced concepts of Java Languages. This tutorial is subdivided into few chapters as shown below

  1. Data Structures
  2. Collections
  3. Generics
  4. Serialization
  5. Networking 
  6. Working with Emails
  7. Multithreading
  8. Getting started with Applets
  9. JavaDoc

Let us know if you find any issues with this tutorial. Also, if you can provide us with your feedback, that always help us improve.

 



Prerequisites

You must have read Part 1 and Part 2 of our tutorial series on Java.

Audience

Beginners or students looking to brush up their Java knowledge

Learning Objectives

To get an understanding on some of the advanced topics of Java.

Author: Subject Coach
Added on: 10th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!