Vous êtes sur la page 1sur 279

Core Java

JAVA Collection Framework :

Collection Framework provides an architecture to store and manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can be performed by Java Collection Framework.

Collection simply means a single unit of objects.

Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection ?

Collection represents a single unit of objects i.e. a group.

What is framework ?

provides ready-made architecture.

represents set of classes and interface.

is optional.

Collection framework

Collection framework represents a unified architecture for storing and manipulating group of object. It has:

Interfaces and its implementations i.e. classes

Algorithm

Hierarchy of Collection Framework :

Let us see the hierarchy of collection framework. The java.util package contains all the classes and interfaces for Collection framework.

Interfaces are mentioned as Green color box Classes are mentioned as purple color box

Core Java

Core Java Iterator interface : ∑ Iterator interface provides the facility of iterating the elements in

Iterator interface :

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface :

public boolean hasNext() → it returns true if iterator has more elements.

public object next() → it returns the element and moves the cursor pointer to the next element.

public void remove() → it removes the last elements returned by the iterator. It is rarely used.

Advantages Of Collection Framework :

Reduces programming effort by providing data structures and algorithms so you don't have to write them yourself.

Increases performance by providing high-performance implementations of data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations.

Collection is resizable and can grow

Core Java

List Of Interfaces and Classes :

 

Hash

Balanced

Interface

Table

Resizable Array

Tree

Linked List

Hash Table + Linked List

Set

List

Deque

Map

Simple Collection Hierarchy :

TreeMap LinkedHashMap Simple Collection Hierarchy : Disadvantages of Collection Framework : ∑ It must cast to

Disadvantages of Collection Framework :

It must cast to correct type.

It can't be done compile-time type checking.

ArrayList :

Uses a dynamic array for storing elements. It extends AbstractList and implements List

can contain duplicate elements

not synchronized

maintains insertion order

random access because array works at the index basis

manipulation slow because a lot of shifting needs to be occurred

ArrayList supports both Iterator and ListIterator for iteration

It allows null values.

It supports Generic which makes Java ArrayList even more powerful because of enhanced type-safety

Core Java

Core Java ∑ ArrayList supports dynamic arrays that can grow as needed . ∑ Standard Java

ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

The ArrayList class supports three constructors. The first constructor builds an empty array list.

1. ArrayList( )

The following constructor builds an array list that is initialized with the elements of the collection c.

2. ArrayList(Collection c)

The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.

3. ArrayList(int capacity)

ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new CopyonWriteArrayList or use Collections.synchronizedList() to create a synchronized List.

Core Java

Example,

List list = Collections.synchronizedList(new ArrayList( ));

CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>(); threadSafeList.add("Java");

threadSafeList.add("J2EE");

threadSafeList.add("Collection");

CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation.

Example Of ArrayList :

1) Creating ArrayList

ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store only String objects

2) Checking size of ArrayList

Size of an ArrayList in Java is total number of elements currently stored in ArrayList.

Int size = stringList.size();

3) Checking Index of an Item in Java Arraylist You can use indexOf() method of ArrayList in Java to find out index of a particular object.

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Int index = stringList.indexOf("Item");//location of Item object in List

Returns the index of the last occurrence of the specified element in this list, or

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does

not contain the element.

the index of the last occurrence of the specified element in this list, or -1 if
Int index = stringList. lastI ndexOf ( "Item" ) ; //location of Item object in

Int index = stringList.lastIndexOf("Item");//location of Item object in

List

Int index = stringList. lastI ndexOf ( "Item" ) ; //location of Item object in List
4)
4)

Checking ArrayList for an Item

Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains() method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.

Core Java

contains(Object o) Returns true if this list contains the specified element

5) Removing an Item from ArrayList

There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself.

Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java.

Since ArrayList allows duplicate its worth noting that remove(Object o) removes the first occurrence of the specified element from this list, if it is present.

In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.

stringList.remove

(

0)

;

 

stringList.remove

(

item

);

Removes the element at the specified position in this list.

Removes the first occurrence of the specified element from this list, if it is

present.

6) Copying data from one ArrayList to another ArrayList in Java

Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java.

Below code will add all elements of stringList to newly created copyOfStringList.

ArrayList<String>copyOfStringList =newArrayList<String>()

;

copyOfStringList.addAll

(

stringList)

;

7) Replacing an element at a particular index

You can use set (int index, E element) method of java ArrayList to replace any element from a particular index.

stringList.set(0

, "Item2")

;

8)
8)

Converting

from ArrayList to Array in Java

Java ArrayList provides you facility to get the array back from your ArrayList.

Core Java

You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element).

String[]itemArray =newString[stringList.size()]

;

String[]returnedArray = stringList.toArray

(

itemArray)

;

9) Converting from Array to ArrayList in Java

This is the simplest way of converting from array to arraylist.

String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures",

"options"};

 

List assetList =Arrays.asList(asset);

 

Its worth to note following point while using Arrays.asList() method for array to arraylist conversion

1) This method returns a List view of underlying array. 2) List returned by this method would be fixed size. 3) Most important point to note is when you change an element into this List corresponding element in original array will also be changed. 4) Another important point is since List is fixed size, you can not add element into it. If you try you will get exception. 5) This is the most efficient way of converting array to arraylist as per my knowledge because it doesn't copy the content of underlying array to create list. 6) From Java 5 or JDK 1.5 onwards this method supports generic so you can generate type safe ArrayList from array.

10) Array to ArrayList by using Collections.addAll method

This example of converting an array to arraylist is not that efficient as the earlier method but its more flexible.

List assetList = new ArrayList(); String[] asset = {"equity", "stocks", "gold", "foriegn exchange", "fixed income", "futures", "options"};

Collections.addAll(assetList, asset);

Important point about this method of array to ArrayList conversion is :

1) Its not as fast as Arrays.asList() but more flexible. 2) This method actually copies the content of the underlying array into ArrayList provided. 3) Since you are creating copy of original array, you can add, modify and remove any element without affecting original one. 4) If you want to provide individual element you can do so by specifying

Core Java

them individually as comma separated. Which is a very convenient way of inserting some more elements into existing list for example,

Collections . addAll ( assetList, "Equity

Collections.addAll(assetList,"Equity

Arbitrage","Mutual Fund");

Collections . addAll ( assetList, "Equity Arbitrage" , "Mutual Fund" ) ;

Derivatives

","Eqity Index

11) This is another great way of converting an array to arraylist.

We are essentially using Collection interface's addAll() method for copying content from one list to another.

Since List returned by Arrays.asList is fixed-size it’s not much of use, this way we can convert that into proper arraylist.

Arraylist newAssetList =newArraylist();

Arraylist newAssetList =newArraylist(); newAssetList.addAll(Arrays.asList(asset));
newAssetList.addAll(Arrays.asList(asset));

newAssetList.addAll(Arrays.asList(asset));

12) Creating Synchronized ArrayList

Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.

List list =Collections.synchronizedList(newArrayList(

));

(or)

CopyOnWriteArrayList<String> threadSafeList = new

CopyOnWriteArrayList<String>();

 

threadSafeList.add("Java");

 

threadSafeList.add("J2EE");

threadSafeList.add("Collection");

 

13) ArrayList to HashSet conversion

Most of Collection class provides a constructor which accepts a Collection object as argument. Which can be used to copy all elements of one Collection into another.

HashSet also provide such constructors which can be used to copy all object from ArrayList to HashSet. But be careful since HashSet doesn't allow duplicates some of the objects will not be included which result in less number of objects.

Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why sometime size of ArrayList doesn't match with size of HashSet after conversion

Example,

HashSet companySet = new HashSet(Collection<? extends E> c);

Core Java

14) If we set ArrayList reference null in Java all the elements inside ArrayList becomes eligible to garbage collection in java , provided there are no more reference exists for those objects.

Difference between Arrays and ArrayList :

Arrays

ArrayList

Arrays are strongly typed. Hence only same type of elements can stored. (Ex. if “A” is an array, here we can store only integer or string or bool etc )

ArrayList are not strongly typed(Loosely typed).

Since strongly typed, boxing and unboxing never happens. This result in better performance

Since Loosely typed, boxing and unboxing happens which results in performance problem

These are fixed in size and will not grow dynamically runtime

They can grow dynamically while runtime

To store and to retrieve we should use integral index

 

Array don’t support Add() and Remove() functions

ArrayList provide sufficient methods to work with like Add()

ADVANTAGES OF USING ARRAYLIST

An array is type specific i.e. one array can only store data of only one data type where as arraylist can store multiple data in the form of objects. So multiple objects of different data types can be stored in arraylist.

In array you cannot increase or decrease the size dynamically where as in arraylist the size can be increased or decreased dynamically.

You can make arraylist readonly.

You can insert element at any location in arraylist.

Arraylist supports BinarySearch.

ArrayLists implement iterable , which means you can easily iterate them.

If an arraylist is modified by another thread while it is being iterated by one thread , then it fails fast , which means you don't end up with unreliable data in the list.

Core Java

DISADVANTAGES OF USING ARRAYLIST

Not efficient for large quantity of data because when the arraylist has to increase its size, its content is copied to a larger arraylist which can be a slow process.

It can only holds Objects i.e. it can’t hold normal data types values such as ‘int’ .

Make ArrayList as ReadOnly :

Example,

Syntax :

public static <T> List<T> unmodifiableList(List<? extends T> list)

Which is present in Collections Class in java.util package

ArrayList al = new ArrayList(); al.add("string"); List alNew = Collections.unmodifiableList(al);

Note : The returned list will be serializable if the specified list is serializable

ArrayList is not Synchronized by Default :

Array list is not synchronized means that object is mutable that means once creating the Array list object that object is calling two threads at a time but one thread is changing the value of object that can be effected by another object so Array list is not thread safe so Array list is not Synchronized by default

Vector vs ArrayList :

Common property of Vector and ArrayList in Java

1) Both Vector and ArrayList are derived from AbstractList and implements List interface, which means both of them are ordered collection and allows duplicates.

2) Another similarity between Vector vs ArrayList is that both are index based Collection and you can use get(index) method to retrieve objects from Vector and ArrayList.

Vector vs ArrayList in Java

1) First and most common difference between Vector vs ArrayList is that Vector is synchronized and thread-safe while ArrayList is neither Synchronized nor

Core Java

thread-safe. Now, What does that mean? It means if multiple thread try to access Vector same time they can do that without compromising Vector's internal state. Same is not true in case of ArrayList as methods like add(), remove() or get() is not synchronized.

2) Second major difference on Vector vs ArrayList is Speed, which is directly related to previous difference. Since Vector is synchronized, its slow

and ArrayList is not synchronized its faster than Vector.

3) Third difference on Vector vs ArrayList is that Vector is a legacy class and initially it was not part of Java Collection Framework.

These were some comparison on Vector vs ArrayList. In Summary use ArrayList if you are using ArrayList in Single threaded environment and use Vector if you need a thread-safe collection. ArrayList is anytime faster than Vector in case thread-safety is not a concern.

What do you mean by Legacy class in JAVA?

Legacy classes are those that were built using Java 1.1 or Java 1.2 API. In general we cannot use this term for java classes. Say for example when Java 1.0 was available Vector was used instead of dynamic array and since there was no ArrayList class people were forced to use Vector for this purpose.

When Java 1.2 was released ArrayList was much more advanced to Vector but has all the features of Vector too. So people started using ArrayList instead of Vector (this again depends on the project requirement, both Vector and ArrayList have their own advantages). And in this case Vector became legacy class.

But this is not constant since in future Sun may introduce a new class that is much more advanced to ArrayList and Vector. And then we call both ArrayList and Vector as legacy classes.

But in general a "legacy" is a term used to define a software created using older version of software.

Example,

public static void main(String[] args) {

List<String> list = new ArrayList<String>(); list.add("Text 1"); list.add("Text 2");
List<String> list = new ArrayList<String>();
list.add("Text 1");
list.add("Text 2");
list.add("Text 3");
System.out.println("#1 normal for loop");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}

Core Java

System.out.println("#2 advance for loop");

for (String temp : list) { System.out.println(temp);

}

System.out.println("#3 while loop"); int j = 0; while (list.size() > j) { System.out.println(list.get(j)); j++;

}

System.out.println("#4 iterator"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next());

}

}

What is Mutable and Immutable Objects in Java ?

An immutable object is an object whose state cannot be modified after it is created.

This is in contrast to a mutable object, which can be modified after it is created

Example ,

int i = 42; //int is of primitive type

Mutable

i

= 43; // OK

final int j = 42;

Immutable

j

= 43; // does not compile. j is final so can't be reassigned

In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String.

class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); str.toLowerCase(); System.out.println(str);

}

}

The output result is

HELLO

HELLO

From the above example, the toLowerCase() method does not impact on the

Core Java

original content in str. What happens is that a new String object "hello" is constructed. The toLowerCase() method returns the new constructed String object's reference. Let's modify the above code:

class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); String str1 = str.toLowerCase();

System.out.println(str1);

}

}

The output result is

HELLO

hello

The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor.

Difference between String and StringBuffer/StringBuilder in Java

Well, the most important difference between String and StringBuffer/StringBuilder

in java is that String object is immutable whereas StringBuffer /

StringBuilder objects are mutable.

By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

So suppose you declare a String object:

String myString = “Hello”;

Next, you want to append “Guest” to the same String. What do you do?

myString = myString + ” Guest”;

When you print the contents of myString the output will be “Hello Guest”. Although

we made use of the same object(myString), internally a new object was

created in the process. So, if you were to do some string operation involving an

Core Java

append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.

Now isn’t that a performance issue? Yes, it definitely is.

Then how do you make your string operations efficient? By using StringBuffer or StringBuilder.

How would that help? Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.

Finally, whats the difference between StringBuffer and StringBuilder? StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

Here’s how you use StringBuilder

Now get out of that bad habit of using String objects to perform operations on strings. With StringBuilder(introduced in J2Se 5.0), you can perform those very append and other such operations more efficiently.

Scene 1: typical coder…. using the same old String object to perform append operations.

String s = “Hello”;

s = s + ” World”;

system.out.println(s);

Core Java

I agree it’ll give you “Hello World”, but fella…. let’s be different from the rest and think about making the code more efficient.

Enter Scene 2.

StringBuilder sb = new StringBuilder(“Hello”);

sb.append(” World”);

system.out.println(sb);

well… thats it!! You’ll get your “Hello World” but in a more efficient way

Simple example to demonstrate that String object is immutable

In my post ‘Difference between String and StringBuffer/StringBuilder’ I told you stuff like String object is immutable( meaning the value stored in the object cannot be changed) and that when you perform operations such as concat or replace, internally a new object is created to hold the result. Below is a simple example that will make you believe that what I said about String object is indeed true!

String s = “Let’s test”;

s.concat(” if the String object is IMMUTABLE”);

System.out.println(s);

Core Java

s = s.concat(” if the String object is IMMUTABLE”);

System.out.println(s);

The output of the above code will be:

Let’s test

Let’s test if the String object is IMMUTABLE

That’s all people! The above piece of code proves that String is immutable and hence the results of operations like concat etc. should be stored into a new object.

LinkedList :

uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.

Contain duplicate elements.

maintains insertion order.

Multiple Null values allowed here

not synchronized.

No random access.

manipulation fast because no shifting needs to be occur.

can be used as list, stack or queue.

Example,

public static void main(String[] args) { System.out.println("Linked List Example!"); LinkedList <Integer>list = new LinkedList<Integer>(); int num1 = 11, num2 = 22, num3 = 33, num4 = 44; int size; Iterator iterator; //Adding data in the list

list.add(num1);

list.add(num2);

list.add(num3);

list.add(num4);

size = list.size();

Core Java

System.out.print( "Linked list data: "); //Create a iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" ");

}

System.out.println(); //Check list empty or not if (list.isEmpty()){

System.out.println("Linked list is empty");

}

else{ System.out.println( "Linked list size: " + size);

}

System.out.println("Adding data at 1st location: 55");

//Adding first

list.addFirst(55);

System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" ");

}

System.out.println();

System.out.println("Now the size of list: " + list.size()); System.out.println("Adding data at last location: 66"); //Adding last or append

list.addLast(66);

System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" ");

}

System.out.println(); System.out.println("Now the size of list: " + list.size()); System.out.println("Adding data at 3rd location: 55"); //Adding data at 3rd position

list.add(2,99);

System.out.print("Now the list contain: ");

Core Java

iterator = list.iterator(); while (iterator.hasNext()){

System.out.print(iterator.next()+" ");

}

System.out.println(); System.out.println("Now the size of list: " + list.size()); //Retrieve first data System.out.println("First data: " + list.getFirst()); //Retrieve lst data System.out.println("Last data: " + list.getLast()); //Retrieve specific data System.out.println("Data at 4th position: " + list.get(3)); //Remove first int first = list.removeFirst();

System.out.println("Data removed from 1st location: " + first); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" ");

}

System.out.println(); System.out.println("Now the size of list: " + list.size()); //Remove last

int last = list.removeLast(); System.out.println("Data removed from last location: " + last); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" ");

}

System.out.println(); System.out.println("Now the size of list: " + list.size()); //Remove 2nd data int second = list.remove(1); System.out.println("Data removed from 2nd location: " + second); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data

Core Java

while (iterator.hasNext()){

System.out.print(iterator.next()+" ");

}

System.out.println();

System.out.println("Now the size of list: " + list.size());

//Remove all

list.clear();

if (list.isEmpty()){

System.out.println("Linked list is empty");

}

else{

System.out.println( "Linked list size: " + size);

}

}

public class LinkedListTest {

public static void main(String[] args) {

List<String> ll = new LinkedList<String>();

ll.add("3");

ll.add("2");

ll.add(null);

ll.add("4");

ll.add("4");

ll.add(null);

ll.add(null);

ll.add(null);

Iterator<String> iter2 = ll.iterator();

while(iter2.hasNext()){

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

}

}

}

Output :

3

2

null

4

4

null

null

null

Doubly Linked List :

Core Java

A doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes.

Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.

The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list.

If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders

from the same data items, but in opposite sequential orders ArrayList vs LinkedList vs Vector :

ArrayList vs LinkedList vs Vector :

List, as its name indicates, is an ordered sequence of elements.

When we talk about List, it is a good idea to compare it with Set which is a set of elements which is unordered and every element is unique. The following is the class hierarchy diagram of Collection.

of elements which is unordered and every element is unique . The following is the class

Core Java

ArrayList vs. LinkedList vs. Vector

From the hierarchy diagram, they all implement List interface.

They are very similar to use. Their main difference is their implementation which causes different performance for different operations.

ArrayList is implemented as a resizable array. As more elements are added to ArrayList, its size is increased dynamically. It's elements can be accessed directly by using the get and set methods, since ArrayList is essentially an array.

LinkedList is implemented as a double linked list. Its performance on add and remove is better than Arraylist, but worse on get and set methods.

Vector is similar with ArrayList, but it is synchronized.

ArrayList is a better choice if your program is thread-safe.

Vector and ArrayList require space as more elements are added. Vector each time doubles its array size, while ArrayList grow 50% of its size each time.

LinkedList, however, also implements DeQue interface which adds more methods than ArrayList and Vector, such as offer(), peek(), poll(), etc.

Note: The default initial capacity of an ArrayList is pretty small. It is a good habit to construct the ArrayList with a higher initial capacity. This can avoid the resizing cost.

Time Duration :

ArrayList add: 13265642 LinkedList add: 9550057 ArrayList get: 1543352 LinkedList get: 85085551 ArrayList remove: 199961301 LinkedList remove: 85768810

The difference of their performance is obvious. LinkedList is faster in add and remove, but slower in get. LinkedList should be preferred if:

There are no large number of random access of element → GET

There are a large number of add/remove operations → Add/Remove

Core Java

List Interface :

List Interface is the subinterface of Collection. It contains methods to insert and delete elements in index basis. It is a factory of ListIterator interface.

public void add(int index,Object element);

public boolean addAll(int index,Collection c);

public object get(int Index position);

public object set(int index,Object element);

public object remove(int index);

public ListIterator listIterator();

public ListIterator listIterator(int i);

ListIterator :

ListIterator Interface is used to traverse the element in backward and

forward direction

public boolean hasNext();

public Object next();

public boolean hasPrevious();

public Object previous();

Difference between List & ListIterator :

There are two Differences :

1) We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.

That is, we can get a Iterator object by using Set and List, see here :

By using Iterator we can retrieve the elements from Collection Object in forward direction only.

Methods in Iterator :

1.hashNext()

2.next()

3.remove()

Iterator ite = Set.iterator(); Iterator ite = List.iterator();

Core Java

2) But we get List Iterator object only from List interface, see here :

where as List Iterator, which allows you to traverse in either directions. That is List Iterators traverse two directions. So it has another methods hasPrevious() & previous() other than Iterator. Methods in ListIterator

1.hasNext()

2.next()

3.previous()

4.hasPrevious()

5.remove()

6.nextIndex()

7.previousIndex()

ListIterator listite = List.listIterator();

i.e., we can't get List Iterator object from Set interface.

Sno

Iterator

List Iterator

1

Using iterator you can visit the elements of collection in the forward direction only

In list iterator you can visit the elements of collection in the forward and backward direction.

2

Using iterator you cannot add elements to collection

Using list Iterator you can add elements to collection

3

Using iterator you can not replace existing object with new object

Using iterator you can replace existing object with new object

4

Using iterator you can not get index of elements

Using list Iterator you can get index of elements list

5

Methods in Iterator :

Methods in ListIterator

hashNext()

hasNext()

next()

next()

remove()

previous()

hasPrevious()

remove()

nextIndex()

previousIndex()

6

Iterator to traverse Set and List and also Map type of Objects

List Iterator can be used to traverse for List type Objects

7

Here cursor position always points to a specific index

Here cursor lies between the element that will be returned by call to previous() and element that will be returned by call to next()

Example,

Core Java

public class IteratorAndListIterator {

public static void main(String[] args) {

List<String> namesList = new ArrayList<String>(); namesList.add("A"); namesList.add("B"); namesList.add("C"); namesList.add("D"); namesList.add("E");

Iterator<String> iterator = namesList.iterator();

System.out.println("Using Iterator"); while (iterator.hasNext()) { System.out.println(iterator.next());

}

System.out.println(); System.out.println("Using List Iterator"); ListIterator<String> listIterator = namesList.listIterator(); while (listIterator.hasNext()) { System.out.print(listIterator.nextIndex()); System.out.println(" " + listIterator.next());

}

System.out.println(); System.out.println("Using ListIterator with Insertion of an

element");

listIterator = namesList.listIterator(); while (listIterator.hasNext()) { System.out.print(listIterator.nextIndex()); if (listIterator.nextIndex() == 2) { listIterator.add("Q");

}

System.out.println(" " + listIterator.next());

}

System.out.println(); System.out.println("Using ListIterator with iteration in reverse order"); listIterator = namesList.listIterator(6); while (listIterator.hasPrevious()) { System.out.print(listIterator.previousIndex()); System.out.println(" " + listIterator.previous());

}

}

}

Output

Using Iterator

A

B

C

D

E

Using List Iterator

1

2

3

4

A

B

C

D

E

Core Java

Using ListIterator with Insertion of an element

1

2

4

5

A

B

C

D

E

Using ListIterator with iteration in reverse order 5 E

4

3

2

1

0 A

D

C

Q

B

Difference between List and Set :

 

List

Set

Is an Ordered grouping of elements

Is an Unordered grouping of elements

List is used to collection of elements with duplicates

Set is used to collection of elements without duplicates

Can be accessed by index

Can not be accessed by index

LinkedList

HashSet (unordered)

ArrayList

LinkedHashSet (ordered)

TreeSet (sorted by natural order or by provided comparator)

SET :

At most Allows one null element

Does not allow duplicate elements

Unordered grouping of elements

Core Java

Can not be accessed by index basis

Extends AbstractSet class implements Set interface

HashSet :

Uses hashtable to store the elements. It extends AbstractSet class and implements Set interface.

Contains unique elements only.

A HashSet is an unsorted, unordered Set

HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.

Example,

class Simple{

public static void main(String args[]){

HashSet al=new HashSet();

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator itr=al.iterator();

while(itr.hasNext()){

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

}

}

}

Output : Ajay

Vijay

Ravi

} } } Output : Ajay Vijay Ravi The HashSet class supports four constructors. The first

The HashSet class supports four constructors. The first form constructs a default hash set:

Core Java

The following constructor form initializes the hash set by using the elements of c.

2) HashSet(Collection c)

The following constructor form initializes the capacity of the hash set to capacity.

The capacity grows automatically as elements are added to the Hash.

3) HashSet(int capacity)

The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments:

4) HashSet(int capacity, float fillRatio)

Make it Synchronized Set :

Set s = Collections.synchronizedSet(new HashSet());

synchronized (s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next());

}

Make it Read-Only Colelction :

Syntax :

public static <T> Set<T> unmodifiableSet(Set<? extends T> s)

Collections.unmodifiableSet(new HashSet());

Example,

public static void main(String[] args) {

// TODO Auto-generated method stub

Set<String> set = new HashSet<String>(); set.add("O"); set.add("C"); set.add("A"); set.add("B");

/*Set<String> linkedSet = new LinkedHashSet<String>(); linkedSet.add("O"); linkedSet.add("C"); linkedSet.add("A"); linkedSet.add("B");

Core Java

for (String str : linkedSet) { System.out.println(str);

}*/

for (String str : set) { System.out.println(str);

}

}

Output : (default ascending order)

A

B

C

O

Using LinkedHashset it displays insertion order like

O

C

A

B

public static void main(String [] args) {

System.out.println( "Collection Example!\n" );

int size;

// Create a collection

HashSet <String>set = new HashSet <String>();

String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";

Iterator iterator;

//Adding data in the collection

set.add(str1);

set.add(str2);

set.add(str3);

set.add(str4);

System.out.print(" set data: ");

//Create a iterator

iterator = set.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() + " ");

}

System.out.println();

// Get size of a collection

size = set.size();

if (set.isEmpty()){

System.out.println(" set is empty");

}

else{

System.out.println( " set size: " + size);

Core Java

}

System.out.println(); // Remove specific data

set.remove(str2);

System.out.println("After removing [" + str2 + "]\n"); System.out.print("Now collection data: "); iterator = set.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " ");

}

System.out.println(); size = set.size();

System.out.println(" set size: " + size + "\n"); //Collection empty set.clear(); size = set.size(); if (set.isEmpty()){ System.out.println(" set is empty");

}

else{

System.out.println( " set size: " + size);

}

}

Readonly collections

public class ReadOnlyCollections {

public static void main(String args[]) {

// creating a list

List godList = Arrays

.asList(new String[] { "Donald", "Dennis", "Ken" });

// making a read-only list

List list = new ArrayList(godList);

list = Collections.unmodifiableList(list);

// checking the reference in a read-only set

Set set = new HashSet(godList);

Collections.unmodifiableSet(set);

Core Java

// the following statement allows to modify the above set as the

// reference is pointing to the original collection therefore it is not

// read-only

set.add("Alan");

// making a read-only map and try to modify it

Map godMap = new HashMap();

godMap.put("TAOCP", "Donald");

godMap.put("C", "Dennis");

godMap = Collections.unmodifiableMap(godMap);

try {

// modifying the read-only map to check what happens

godMap.put("Unix", "Ken");

} catch (UnsupportedOperationException e) {

System.out.println("You cannot modify a read only collection!");

}

}

}

LinkedHashSet :

Contains unique elements only like HashSet.

cannot modify a read only collection!"); } } } LinkedHashSet : ∑ Contains unique elements only

Core Java

It extends HashSet class and implements Set interface.

Maintains insertion order.

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.

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.

HashSet vs LinkedHashSet :

The only difference is that the LinkedHashSet maintains the order of the items added to the Set.

It does this by maintaining a doubly linked list containing the hash and the original order of the items.

According to Sun, the LinkedHashSet should run nearly as fast as the HashSet.

TreeSet :

Contains unique elements only like HashSet.

The TreeSet class implements NavigableSet interface that extends the SortedSet interface

Maintains ascending order.

It extends AbstractSet class

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Its not synchronized. To make it as synchronized set do the following,

To make it as synchronized set do the following, SortedSet s = Collections.synchronizedSortedSet(new TreeSet(

SortedSet s = Collections.synchronizedSortedSet(new TreeSet( ));

Example,

Core Java

public static void main(String[] args) {

System.out.println("Tree Set Example!\n"); TreeSet tree = new TreeSet();

tree.add(12);

tree.add(63);

// Output 12, 34, 45, 63

tree.add(34);

tree.add(45);

// here it test it's sorted, 63 is the last element. see output below

Iterator iterator = tree.iterator(); System.out.print("Tree set data: ");

//Displaying the Tree set data

while (iterator.hasNext()) { System.out.print(iterator.next() + " ");

}

System.out.println();

//Check empty or not

if (tree.isEmpty()) { System.out.print("Tree Set is empty.");

}

else { System.out.println("Tree Set size: " + tree.size());

}

//Retrieve first data from tree set

System.out.println("First data: " + tree.first());

//Retrieve last data from tree set

System.out.println("Last data: " + tree.last());

if (tree.remove(45)) { // remove element by value

System.out.println("Data is removed from tree set");

}

else { System.out.println("Data doesn't exist!");

}

System.out.print("Now the tree set contain: "); iterator = tree.iterator();

//Displaying the Tree set data

while (iterator.hasNext()) { System.out.print(iterator.next() + " ");

}

System.out.println(); System.out.println("Now the size of tree set: " + tree.size());

//Remove all

tree.clear(); if (tree.isEmpty()) { System.out.print("Tree Set is empty.");

}

else { System.out.println("Tree Set size: " + tree.size());

}

}

Core Java

HashSet vs TreeSet vs LinkedHashSet :

In a set, there are no duplicate elements. That is one of the major reasons to use a set.

There are 3 commonly used implementations of Set in Java:

1) HashSet,

2) TreeSet and

3) LinkedHashSet.

When and which to use is an important question.

In brief, if we want a fast set, we should use HashSet;

if we need a sorted set, then TreeSet should be used;

if we want a set that can be read by following its insertion order, LinkedHashSet should be used.

HashSet is Implemented using a hash table. Elements are not ordered. The add, remove, and contains methods has constant time complexity

O(1).

TreeSet is implemented using a tree structure(red-black tree in algorithm book). The elements in a set are sorted, but the add, remove, and contains methods has time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.

LinkedHashSet is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order of insertion. The time complexity of basic methods is O(1).

What is common in HashSet and TreeSet in Java .?

1)Both HashSet and TreeSet implements java.util.Set interface which means they follow contract of Set interface and doesn't allow any duplicates.

2)Both HashSet and TreeSet are not thread-safe and not synchronized. Though you can make them synchronized by using Collections.synchronizedSet() method.

3) Third similarity between TreeSet and HashSet is that, Iterator of both classes are fail-fast in nature. They will throw ConcurrentModificationException if Iterator is modified once Iterator is created. this is not guaranteed and application code should not rely on this code but Java makes best effort to fail as soon as it detects structural change in underlying Set.

Core Java

HashSet vs TreeSet in Java

Now let's see couple of differences between HashSet vs TreeSet in Java. This is enough to decide whether you should use HashSet or TreeSet in a given scenario.

1) First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of element is not required.

2) Second difference between HashSet and TreeSet is that HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException as shown in below example :

HashSet <String> hashSet =new HashSet<String>(); hashSet.add("Java"); hashSet.add(null);
HashSet <String> hashSet =new HashSet<String>();
hashSet.add("Java");
hashSet.add(null);
TreeSet <String> treeSet =new TreeSet<String>();
treeSet.add("C++");
treeSet.add(null);//Java.lang.NullPointerException
Output:
Exceptionin thread"
main"java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:541)
at java.util.TreeSet.add(TreeSet.java:238)
at test.CollectionTest.main(CollectionTest.java:27)
JavaResult:1

3) Another significant difference between HashSet and TreeSet is that , HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.

4) One more difference between HashSet and TreeSet which is worth remembering is that HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet

5) Now most important difference between HashSet and TreeSet is ordering. HashSet doesn't guaranteed any order while TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java.

Core Java

Comparable Interface : (for sorting purpose)

Comparable interface is used to order the objects of user-defined class.

This interface is found in java.lang package and contains only one method named compareTo(Object).

It provide only single sorting sequence i.e. you can sort the elements based on single data member only.

public int compareTo(Object obj) is used to compare the current object with the specified object.

Collections class provides static methods for sorting the elements of collection.

If collection elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.

Collections class provides methods for sorting the elements of List type elements.

public void sort(List list) is used to sort the elements of List. List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.

If any class implements comparable interface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort(). Object will be sort on the basis of compareTo method in that class.

Example ,

class Student implements Comparable{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

}

Core Java

public int compareTo(Object obj){

Student st=(Student)obj;

if(age==st.age)

return 0;

else if(age > st.age)

return 1;

else

return -1;

}}

Comparator interface :

Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains only one method named compare(Object obj1,Object obj2).

It provides multiple sorting sequence i.e. you can sort the elements based on any data member.

public int compare(Object obj1,Object obj2) compares the first object with second object.

Example,

1) class AgeComparator implements Comparator{

public int Compare(Object o1,Object o2){

Student s1=(Student)o1;

Student s2=(Student)o2;

if(s1.age==s2.age)

return 0;

else if(s1.age>s2.age)

return 1;

else

return -1;

}

}

Core Java

2) class NameComparator implements Comparator{ public int Compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2;

return s1.name.compareTo(s2.name);

}

}

3) class Simple{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Student(101,"Vijay",23)); al.add(new Student(106,"Ajay",27)); al.add(new Student(105,"Jai",21)); System.out.println("Sorting by Name

");

Collections.sort(al,new NameComparator()); Iterator itr=al.iterator(); while(itr.hasNext()){ Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

}

System.out.println("sorting by age

");

Collections.sort(al,new AgeComparator()); Iterator itr2=al.iterator();

while(itr2.hasNext()){

Student st=(Student)itr2.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); }}}

Comparator vs Comparable :

Core Java

Parameter

Comparable

Comparator

Sorting logic

Sorting logic must be in same class whose objects are being sorted. Hence

Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using

this is called natural ordering of objects

id, name etc. Class whose objects to be sorted Class whose objects to be do not need to implement this

sorted must implement this interface. Some other class can

Implementation

interface. e.g Country class needs to implement comparable to collection of country object by id

implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

int compareTo(Object o1) This method compares this

object with o1 object and int compare(Object o1,Object o2)

returns a integer. Its value has following meaning

This method compares o1 and o2 objects. and returns a integer. Its value has following meaning.

Sorting method

1. positive – this object 1. positive – o1 is greater than

is greater than o1

o2

2. zero – this object

2. zero – o1 equals to o2

equals to o1

3. negative – o1 is less than o1

3. negative – this object

Calling method

is less than o1 Collections.sort(List) Here objects will be sorted on the basis of CompareTo method

Collections.sort(List, Comparator) Here objects will be sorted on the basis of Compare method in Comparator

Package

Sorting

Java.lang.Comparable Java.util.Comparator Accepts Single Sorting

Accepts Multiple Sorting Sequence

Sequence

Sequence

Example,

package org.arpit.javapostsforlearning; //If this.cuntryId < country.countryId:then compare method will return -1 //If this.countryId > country.countryId:then compare method will return 1 //If this.countryId==country.countryId:then compare method will return 0 public class Country implements Comparable{ int countryId; String countryName;

public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName;

}

@Override

Core Java

public int compareTo(Object arg0) {

Country country=(Country) arg0; return (this.countryId < country.countryId ) ? -1:

(this.countryId > country.countryId ) ? 1:0 ;

}

public int getCountryId() { return countryId;

}

public void setCountryId(int countryId) { this.countryId = countryId;

}

public String getCountryName() { return countryName;

}

public void setCountryName(String countryName) { this.countryName = countryName;

}

}

ComparableMain :

package org.arpit.javapostsforlearning;

import java.util.ArrayList; import java.util.Collections; import java.util.List;

public class ComparableMain {

/** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');

List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);

System.out.println('Before Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country)

listOfCountries.get(i);

System.out.println('Country Id:

'+country.getCountryId()+'||'+'Country name: '+country.getCountryName());

}

Collections.sort(listOfCountries);

Core Java

System.out.println('After Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country)

listOfCountries.get(i);

System.out.println('Country Id:

'+country.getCountryId()+'|| '+'Country name:

'+country.getCountryName());

}

}

}

Before Sort

Country Id: 1||Country name: India Country Id: 4||Country name: China Country Id: 3||Country name: Nepal Country Id: 2||Country name: Bhutan After Sort

Country Id: 1|| Country name: India Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China

:

:

Comparator Example,

package org.arpit.javapostsforlearning;

public class Country{ int countryId; String countryName;

public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName;

}

public int getCountryId() { return countryId;

}

public void setCountryId(int countryId) { this.countryId = countryId;

}

public String getCountryName() { return countryName;

}

public void setCountryName(String countryName) { this.countryName = countryName;

}

}

Core Java

package org.arpit.javapostsforlearning;

import java.util.Comparator; //If country1.getCountryId()<country2.getCountryId():then compare method will return -1 //If country1.getCountryId()>country2.getCountryId():then compare method will return 1 //If country1.getCountryId()==country2.getCountryId():then compare method will return 0 public class CountrySortByIdComparator implements Comparator<Country>{

@Override public int compare(Country country1, Country country2) {

return (country1.getCountryId() < country2.getCountryId() ) ? -1:

(country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;

}

}

package org.arpit.javapostsforlearning;

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;

public class ComparatorMain {

/** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');

List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);

System.out.println('Before Sort by id : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country)

listOfCountries.get(i);

System.out.println('Country Id:

'+country.getCountryId()+'||'+'Country name: '+country.getCountryName());

}

Collections.sort(listOfCountries,new

CountrySortByIdComparator());

System.out.println('After Sort by id: '); for (int i = 0; i < listOfCountries.size(); i++) {

listOfCountries.get(i);

Core Java

Country country=(Country)

System.out.println('Country Id:

'+country.getCountryId()+'|| '+'Country name:

'+country.getCountryName());

}

//Sort by countryName Collections.sort(listOfCountries,new Comparator<Country>() {

o2) {

@Override public int compare(Country o1, Country

return

o1.getCountryName().compareTo(o2.getCountryName());

});

}

System.out.println('After Sort by name: '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country)

listOfCountries.get(i);

System.out.println('Country Id:

'+country.getCountryId()+'|| '+'Country name:

'+country.getCountryName());

}

}

}

Before Sort by id :

Country Id: 1||Country name: India Country Id: 4||Country name: China Country Id: 3||Country name: Nepal Country Id: 2||Country name: Bhutan After Sort by id:

Country Id: 1|| Country name: India Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China After Sort by name:

Country Id: 2|| Country name: Bhutan Country Id: 4|| Country name: China Country Id: 1|| Country name: India Country Id: 3|| Country name: Nepal

Core Java

Map :

A map contains values based on the key i.e. key and value pair.

Each

Map contains only unique elements.

The Map interface is not an extension of Collection interface.

Instead the interface starts of it’s own interface hierarchy, for maintaining key-value associations.

The interface describes a mapping from keys to values, without duplicate keys

The Map interface provides three (3) collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings.

pair

is known as an entry.

keySet → set of keys

values → collection of values

entrySet → set of key-value mappings

Three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.

Methods :

1. public Object put(object key,Object value)

2. public void putAll(Map map)

3. public Object remove(object key)

4. public Object get(Object key)

5. public boolean containsKey(Object key)

6. public boolean containsValue(Object value)

7. public Set keySet()

8. public Set entrySet()

Entry :

Entry is the subinterface of Map. So we will access it by Map.Entry name.

It provides methods to get key and value.

Methods :

1. public Object getKey()

Core Java

Why use Map.Entry .?

If you just need keys, use keySet(). If you just need values, use values(). If you're going to use keys and values in your subsequent code, then you're best off using entrySet().

I frequently see people do this without entrySet(), and it usually looks something like this:

1.

for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {

2.

 

Foo key = (Foo) it.next();

 

3.

 

Bar value = (Bar) map.get(key);

 

4.

 

// now do something with key and value

 

5.

}

 

This works, but it's making the JVM do extra work for no good reason. Every time you call get() you're making the JVM spend time doing a hashcode lookup, or navigating a tree and evaluating a comparator. These operations may be fast, or not, but why do them if you don't have to? A Map.Entry gives you both key and value, together, in the most efficient manner possible.

1.

for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {

2.

 

Map.Entry e = (Map.Entry) it.next();

 

3.

 

Foo key = (Foo) e.getKey();

 

4.

 

Bar value = (Bar) e.getValue();

 

5.

 

// now do something with key and value

   

6.

}

 

Under JDK 5 and later it's a little nicer:

1.

for (Map.Entry<Foo,Bar> e : map.entrySet()) {

2.

 

Foo key = e.getKey();

 

3.

 

Bar value = e.getValue();

 

4.

 

// now do something with key and value

 

5.

}

 

The SortedMap interface (with the implementation TreeMap) should be your friend.

The interface has the methods:

keySet() which returns a set of the keys in ascending order values() which returns a collection of all values in the ascending order of the corresponding keys

However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

Example,

public static void main(String[] args) {

Map<Integer, String> hashMap = new HashMap<Integer, String>(); hashMap.put(10, null);

Core Java

hashMap.put(2, "First"); hashMap.put(1, "First"); hashMap.put(null, null); hashMap.put(null, "Second"); hashMap.put(3, null);

for (Integer key : hashMap.keySet()) { System.out.println( key + " " + hashMap.get(key));

}

}

Output:

null Second

1 First

2 First

3 null

10 null

HashMap :

A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.

It contains only unique elements.

It may have one null key and multiple null values.

It maintains no order.

Hierarchy of HashMap Class :

class Simple{

public static void main(String args[]){

HashMap hm=new HashMap();

hm.put(100,"Amit");

hm.put(101,"Vijay");

hm.put(102,"Rahul");

Set set=hm.entrySet();

Iterator itr=set.iterator();

while(itr.hasNext()){

Iterator itr=set.iterator(); while(itr.hasNext()){ Map.Entry m=(Map.Entry)itr.next();

Map.Entry m=(Map.Entry)itr.next();

System.out.println(m.getKey()+" "+m.getValue());

}

}

}

Core Java

The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

The HashMap class supports four constructors. The first form constructs a default hash map:

HashMap( )

The second form initializes the hash map by using the elements of m:

HashMap(Map m)

The third form initializes the capacity of the hash map to capacity:

HashMap(int capacity)

The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments:

HashMap(int capacity, float fillRatio)

LinkedHashMap :

A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.

It contains only unique elements.

It may have one null key and multiple null values.

It is same as HashMap instead maintains insertion order.

∑ It may have one null key and multiple null values. ∑ It is same as

Tree Map :

Core Java

A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.

It contains only unique elements.

It cannot have null key but can have multiple null values.

It is same as HashMap instead maintains ascending order.

It is same as HashMap instead maintains ascending order . Example, public static void main(String[] args)

Example,

public static void main(String[] args) {

// Create a TreeMap and populate it with elements TreeMap treeMap = new TreeMap();

treeMap.put("key_1","element_1");

treeMap.put("key_2","element_2");

treeMap.put("key_3","element_3");

// Get a set of all the entries (key - value pairs) contained in the TreeMap Collection entrySet = treeMap.entrySet();

// Obtain an Iterator for the entries Set Iterator it = entrySet.iterator();

// Iterate through TreeMap entries System.out.println("TreeMap entries : "); while(it.hasNext())

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

}

TreeMap entries :

key_1=element_1

key_2=element_2

key_3=element_3

HashTable :

Core Java

A HashTable is an Array of list.

Each list is known as a bucket. The position of the bucket is identified by calling hashcode() method.

A Hashtable contains values based on the key.

It implements the Map interface and extends Dictionary class.

It contains only unique elements

It may not have any null key or value

It is synchronized

Syntax :

public class Hashtable<K,V> extends Dictionary<K,V> implements