Java Collections Framework - HudaTutorials.com

prettybadelyngeΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

142 εμφανίσεις

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

1


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 th
e 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 u
nit, 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 enca
psulate both the data structures and the algorithms associated with
these abstractions.

With the Java Collections Framework the programmer
easily define
higher
level data

abstractions, suc
h as stacks, queues, and thread
safe collections.


Y
ou should be ab
le 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 d
ata structure, without altering the rest of your code.
The following diagram
s

shows the framework interface hierarchy.


What Is a Collections Framework?


A collections framework is a unified architecture for representing and manipulating
collections. All c
ollections 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, interface
s 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 sor
ting, 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 functional
ity.






http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

2


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 th
e 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
A
PIs.

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 easi
ly 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. Th
ere 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 des
ign 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 s
tandard
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, interf
aces and utility
classes.




Collection Classes

AbstractCollection

AbstractList

AbstractMap

AbstractQueue

AbstractSequentialList

AbstractSet

ArrayDeque

ArrayList

Arrays

Collections

EnumMap

EnumSet

HashMap

HashSet

Hashtable

IdentityHashMap

LinkedHashMap

Linke
dHashSet

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

3


LinkedList

PriorityQueue

TreeMap

TreeSet

Vector

WeakHashMap




Collection Interfaces

Collection

Set

List

Queue

Deque

Map

SortedSet

SortedMap

NavigableSet

NavigableMap

BlockingQueue

BlockingDeque

ConcurrentMap

ConcurrentNavigableMap



java.util.
Array
s

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;


pub
lic 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



Arr
ays.sort(arr);

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

4





//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 DEC
LARATION 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




Syst
em.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));


}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

5


}


Note:

When filling an object array, the fill() method will copy the sa
me 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);


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

6




//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 provide
s 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 s
imilarities 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 AbstractSe
t, 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[])


{

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

7




//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.ArrayLi
st 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);

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

8





//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 ja
va.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


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

9




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



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




//ADD ELEMENT TO Lis
t 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());




//CHE
CK 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","Jav
a Tutorials","C Tutorials"};



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




//java.util.List DECLARATION



List s, s2;

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

10





//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 j
ava.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.ut
il.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 ObjectO
utputStream(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.prin
tln("Error Occurred : " + e.getMessage());



}


}

}


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

11


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;





//FileInputStr
eam 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 */

/* Sa
ve 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[] = {"Hud
a 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));

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

12





//java.util.List OUTPUT



ListIterator itr = s.listIterator();



w
hile(itr.hasNext())



{




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



}




System.out.println();



System.out.println("
-----

Reverse Order
-----
");



System.out.println();




//java.util.List OUTPUT IN REVERSE ORDER



ListIterator itr2 = s.listIterator(s.size());



while(itr2.hasPrevious())



{




System.out.println(itr2.previous());



}


}

}



java.util.
LinkedList

Class


The LinkedList class is a doubly linked list, which internally maintains references to the
previous and next element at each node in the list.
Li
nked list implementation of the List
interface. Implements all optional list operations, and permits all elements (including
null).

The class implements the Deque interface, providing first
-
in
-
first
-
out queue
operations for add, poll, along with other sta
ck and deque operations.


Note that this implementation is not synchronized. If multiple threads access a linked list
concurrently, and at least one of the threads modifies the list structurally, it must be
synchronized externally.

if the list is structur
ally modified at any time after the iterator
is created, in any way except through the Iterator's own remove or add methods, the
iterator will throw a ConcurrentModificationException.


LinkedList

class has following constructors.


LinkedList()

Constructs a
n empty list.


LinkedList(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.


In this tutorial you can learn about java.util.
LinkedList

class

and it
s examples
. And also
learn how to use java.util.
LinkedList

class.


/* java.util.LinkedList class Example */

/* Save with file name LinkedListExample.java */


import java.util.LinkedList;


public class LinkedListExample

{

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

13



public static void main(String arg
s[])


{



//java.util.LinkedList DECLARATION



LinkedList al;




//java.util.LinkedList OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



al = new LinkedList();




//ADD AN ELEMENT



al.add("Huda Tutorials");



al.add("Java Tutorials");




//DUPLICATES ARE A
LLOWED



al.add("Huda Tutorials");



al.add("C Tutorials");



al.add("CPP Tutorials");




//null ALLOWED



al.add(null);




//RETURNS COUNT OF ELEMENTS LinkedList CONTAINS



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




//java.util.LinkedList OUT
PUT



System.out.println(al);


}

}


The following example shows how to use LinkedList with Iterator.


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

/* Save with file name LinkedListExample2.java */


import java.util.LinkedList;

import java.util.Iterator;


pub
lic class LinkedListExample2

{


public static void main(String args[])


{



//java.util.LinkedList DECLARATION



LinkedList al;




//java.util.LinkedList OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



al = new LinkedList();




//ADD AN ELEMENT



al.add("H
uda Tutorials");



al.add("Java Tutorials");




//DUPLICATES ARE ALLOWED



al.add("Huda Tutorials");



al.add("C Tutorials");



al.add("CPP Tutorials");


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

14




//null ALLOWED



al.add(null);




//RETURNS COUNT OF ELEMENTS LinkedList CONTAINS



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




//java.util.LinkedList OUTPUT



Iterator itr = al.iterator();



while(itr.hasNext())



{




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



}


}

}


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


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

/* Save with file name LinkedListExample3.java */


import java.util.LinkedList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;


public class LinkedListExample3

{


public static void ma
in(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 LinkedList(Arrays.asList(elements));




//java.util.List
OUTPUT



Iterator itr = s.iterator();



while(itr.hasNext())



{




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



}


}

}


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

/* Save with file name LinkedListExample4.java */


import java.util.LinkedList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;


public class LinkedListExample4

{


public static void main(String args[])


{



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

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

15




List s; //java.util.List DECLARATION




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



s = new LinkedList(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 T
utorials");




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.LinkedList class Example 5 */

/* Save with file name LinkedListExample5.java */


import java.util.LinkedList;

import java.util.List;

import java.util.Arrays;

import java.util.Iterator;


publi
c class LinkedListExample5

{


public static void main(String args[])


{



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



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


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

16




//java.util.List DECLARATION



List s, s2;




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



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



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




//COMPARE TWO COLLECTIONS



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




//CONTA
INS COLLECTION IN OTHER COLLECTION



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


}

}

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


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

/* Save with file name LinkedListExample6.java *
/


import java.util.LinkedList;

import java.util.List;

import java.util.Arrays;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;


public class LinkedListExample6

{


public static void main(String args[])


{



try



{




String elements[]

= {"Huda Tutorials","Java Tutorials","Android Tutorials"};





//java.util.LinkedList DECLARATION




List s;





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




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





//FileOutputStream CREATION




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





//ObjectOutputStream CREATION




ObjectOutputStream oos = new ObjectOutputStream(fos);





//WRITE List OBJECT TO ObjectOutputStream




oos.writeObject(s);






//CLOSE THE ObjectOutputStream




oos.cl
ose();




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



}



catch(Exception e)



{




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



}


}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

17


}


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


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

/* Save with file name LinkedListExample7.java */


import java.util.LinkedList;

import java.util.List;

import java.util.Arrays;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class LinkedListEx
ample7

{


public static void main(String args[])


{



try



{




//java.util.LinkedList DECLARATION




List s;





//FileInputStream CREATION




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





//ObjectInputStream CREATION




ObjectInputStream oi
s = 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 LinkedList with Arrays, Iterator and ListIterator.


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

/* Save with file name LinkedListExample8.java */


import java.util.LinkedList;

import java.util.Arrays;

import java.util.List
Iterator;

import java.util.Iterator;


public class LinkedListExample8

{


public static void main(String args[])


{



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



LinkedList s; //java.util.LinkedList DECLARATION


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

18




//java.util.Li
st OBJECT CREATION USING ARRAY AS LIST



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




//java.util.List OUTPUT



ListIterator itr = s.listIterator();



while(itr.hasNext())



{




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



}




System.out.println();



System.out.
println("
-----

Reverse Order
-----
");



System.out.println();




//java.util.List OUTPUT IN REVERSE ORDER



Iterator itr2 = s.
descendingIterator()
;



while(itr2.hasNext())



{




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



}


}

}


/* java.util.LinkedList class Exam
ple 9*/

/* Save with file name LinkedListExample9.java */


import java.util.LinkedList;


public class LinkedListExample9

{


public static void main(String args[])


{



//java.util.LinkedList DECLARATION



LinkedList al;




//java.util.LinkedList OBJECT CRE
ATION



//USING DEFAULT CONSTRUCTOR



al = new LinkedList();




//ADD AN ELEMENT



al.addFirst("Java Tutorials");




//ADD AN ELEMENT AT LAST



al.addLast("C Tutorials");



al.addLast("CPP Tutorials");




//ADD AN ELEMENT AT FIRST



al.addFirst("Huda Tutor
ials2");




//ADD AN ELEMENT



al.push("Huda Tutorials");




//java.util.LinkedList OUTPUT



System.out.println(al);




//GET THE FIRST ELEMENT



System.out.println("First Element : " + al.getFirst());

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

19





//GET THE LAST ELEMENT



System.out.println("Last E
lement : " + al.getLast());




//GET THE HEAD (FIRST) ELEMENT



System.out.println("Head (First) Element : " + al.peek());



}

}


j
ava.util.
Hashtable Class


A Hashtable is a specialized Dictionary that relies on a hashing algorithm to convert keys
into a m
echanism to

look up values in the dictionary. The hashing algorithm provides a
quick way to convert any object into

something that

can serve as a look−up mechanism.

This class implements a hashtable, which maps keys to values. Any non
-
null object can
be used as a key or as a value.

To successfully store and retrieve objects from a
hashtable, the objects used as keys must implement th
e hashCode method and the
equals method.


An instance of Hashtable has two parameters that affect its performance: initial capacity
and load factor. The capacity is the number of buckets in the hash table, and the initial
capacity is simply the capacity a
t the time the hash table is created. Note that the hash
table is open: in the case of a "hash collision", a single bucket stores multiple entries,
which must be searched sequentially. The load factor is a measure of how full the hash
table is allowed to g
et before its capacity is automatically increased. The initial capacity
and load factor parameters are merely hints to the implementation. The exact details as
to when and whether the rehash method is invoked are implementation
-
dependent.


Generally, the d
efault load factor (.75) offers a good tradeoff between time and space
costs. Higher values decrease the space overhead but increase the time cost to look up
an entry (which is reflected in most Hashtable operations, including get and put).


The initial ca
pacity controls a tradeoff between wasted space and the need for rehash
operations, which are time
-
consuming. No rehash operations will ever occur if the initial
capacity is greater than the maximum number of entries the Hashtable will contain
divided by i
ts load factor. However, setting the initial capacity too high can waste space.


If many entries are to be made into a Hashtable, creating it with a sufficiently large
capacity may allow the entries to be inserted more efficiently than letting it perform
a
utomatic rehashing as needed to grow the table.


/* java.util.Hashtable class Example */

/* Save with file name HashtableExample.java */


import java.util.Hashtable;

import java.util.Enumeration;


public class HashtableExample

{


public static void main(St
ring args[])


{



//java.util.Hashtable DECLARATION



Hashtable<String,Integer> h;




//java.util.Hashtable OBJECT CREATION

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

20




//USING DEFAULT CONSTRUCTOR



h = new Hashtable<String,Integer>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("T
WO", new Integer(2));



h.put("THREE", new Integer(3));




//Hashtable OUTPUT



Enumeration e = h.elements();



while(e.hasMoreElements())



{




System.out.println(e.nextElement());



}


}

}


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

/* Save with file nam
e HashtableExample2.java */


import java.util.Hashtable;

import java.util.Enumeration;

import java.util.Collection;

import java.util.Iterator;


public class HashtableExample2

{


public static void main(String args[])


{



//java.util.Hashtable DECLARATION



Hashtable<String,Integer> h;




//java.util.Hashtable OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new Hashtable<String,Integer>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3
));




//Hashtable KEYS OUTPUT



Enumeration e = h.keys();



int i=1;



while(e.hasMoreElements())



{




System.out.println("Key " + i++ + " : " + e.nextElement());



}




//Hashtable VALUES OUTPUT



Collection c = h.values();



Iterator values = c.iterat
or();



int j=1;



while(values.hasNext())



{




System.out.println("Value " + j++ + " : " + values.next());



}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

21



}

}


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

/* Save with file name HashtableExample3.java */


import java.util.Hashtable;

import java.util.
Enumeration;


public class HashtableExample3

{


public static void main(String args[])


{



//java.util.Hashtable DECLARATION



Hashtable<String,Integer> h;




//java.util.Hashtable OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new Hashtable<String,I
nteger>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




System.out.println("isEmpty : " + h.isEmpty());




//RETURNS THE NUMBER OF KEYS IN THIS Hashtable



System.out.println("noo
f Keys : " + h.size());




System.out.println("Key ONE value : " + h.get("ONE"));




System.out.println("Contains key THREE : " + h.containsKey("THREE"));




System.out.println("Contains value 2 : " + h.contains (new Integer(2)));


}

}


The following examp
le shows how to save Hashtable into file.


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

/* Save with file name HashtableExample4.java */


import java.util.Hashtable;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;


public class HashtableEx
ample4

{


public static void main(String args[])


{



try



{




//java.util.Hashtable DECLARATION




Hashtable<String,Integer> h;





//java.util.Hashtable OBJECT CREATION

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

22





//USING DEFAULT CONSTRUCTOR




h = new Hashtable<String,Integer>();





//ADD AN

ELEMENTS




h.put("ONE", new Integer(1));




h.put("TWO", new Integer(2));




h.put("THREE", new Integer(3));





//FileOutputStream CREATION




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





//ObjectOutputStream CREATION




ObjectOutpu
tStream oos = new ObjectOutputStream(fos);





//WRITE Set OBJECT TO ObjectOutputStream




oos.writeObject(h);






//CLOSE THE ObjectOutputStream




oos.close();




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



}



catch(Exception e)



{




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



}


}

}


The following example shows how to retrieve Hashtable from file.


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

/* Save with file name HashtableExample5.java */


import java.util.Hashtable;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class HashtableExample5

{


public static void main(String args[])


{



try



{




//java.util.Hashtable DECLARATION




Hashtable<String,Integer> h;





//FileInputStream CREATION




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





//ObjectInputStream CREATION




ObjectInputStream ois = new ObjectInputStream(fis);





//READ Hashtable OBJECT FROM ObjectInputStream




h = (Hashtable) ois.readObject();




ois.close();




System.out.println(h);



}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

23




catch(Exception e)



{




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



}


}

}



java.util.
HashSet

Class


The Collection Framework introduces the HashSet collection. This implementation is
backed by a hash table (
HashMap, actually) for storing unique elements. The backing
hash table ensures that duplicate elements are avoided as each element is stored and
retrieved through its hash code, providing constant retrieval time.


It makes no guarantees as to the iteration

order of the set; in particular, it does not
guarantee that the order will remain constant over time. This class permits the null
element.

Most of the HashSet functionality is provided through the AbstractCollection
and AbstractSet superclasses, which Ha
shSet shares with TreeSet.


HashSet

class has following constructors.


HashSet()

Constructs a new, empty set; the backing HashMap instance has default initial capacity
(16) and load factor (0.75).


HashSet(Collection<? extends E> c)

Constructs a new set co
ntaining the elements in the specified collection.


HashSet(int initialCapacity)

Constructs a new, empty set; the backing HashMap instance has the specified initial
capacity and default load factor (0.75).


HashSet(int initialCapacity, float loadFactor)

Co
nstructs a new, empty set; the backing HashMap instance has the specified initial
capacity and the specified load factor.


In this tutorial you can learn about java.util.
HashSet

class

and its examples
. And also
learn how to use java.util.
HashSet

class.


/*

java.util.HashSet class Example */

/* Save with file name HashSetExample.java */


import java.util.HashSet;


public class HashSetExample

{


public static void main(String args[])


{



//java.util.HashSet DECLARATION



HashSet hs;




//java.util.HashSet OB
JECT CREATION



//USING DEFAULT CONSTRUCTOR



hs = new HashSet();

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

24





//ADD AN ELEMENT



hs.add("Huda Tutorials");



hs.add("Java Tutorials");




//DUPLICATES NOT ALLOWED



hs.add("Huda Tutorials");



hs.add("C Tutorials");



hs.add("CPP Tutorials");




//R
ETURNS COUNT OF ELEMENTS HashSet CONTAINS



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




//java.util.HashSet OUTPUT



System.out.println(hs);


}

}


The following example shows how to use HashSet with Iterator.


/* java.util.HashSet class Example

2 */

/* Save with file name HashSetExample2.java */


import java.util.HashSet;

import java.util.Iterator;


public class HashSetExample2

{


public static void main(String args[])


{



//java.util.HashSet DECLARATION



HashSet hs;




//java.util.HashSet OBJ
ECT CREATION



//USING DEFAULT CONSTRUCTOR



hs = new HashSet();




//ADD AN ELEMENT



hs.add("Huda Tutorials");



hs.add("Java Tutorials");




//DUPLICATES NOT ALLOWED



hs.add("Huda Tutorials");



hs.add("C Tutorials");



hs.add("CPP Tutorials");




//RE
TURNS COUNT OF ELEMENTS HashSet CONTAINS



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




//java.util.HashSet OUTPUT



Iterator itr = hs.iterator();



while(itr.hasNext())



{




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



}


}

}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

25



The following example show
s how to use HashSet with Arrays, Set and Iterator.


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

/* Save with file name HashSetExample3.java */


import java.util.HashSet;

import java.util.Set;

import java.util.Arrays;

import java.util.Iterator;


public class H
ashSetExample3

{


public static void main(String args[])


{



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



Set s; //java.util.Set DECLARATION




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



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




//java.util.Set OUTPUT



Iterator itr = s.iterator();



while(itr.hasNext())



{




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



}


}

}


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

/* Save with file name HashSetExample4.java */


import java.util.HashSet;

import java.util.Set;

import java.util.Arrays;

import java.util.Iterator;


public class HashSetExample4

{


public static void main(String args[])


{



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



Set s; //java.util.Set DECLARATI
ON




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



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




//ADD ELEMENT TO Set COLLECTION



s.add("NetBeans Tutorials");




//DISPLAY SIZE OF THE Set COLLECTION



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




//CHECK THE Set COLLECTION IS EMPTY



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


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

26




//CHECK THE GIVEN ELEMENT IN Set COLLECTION



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




//java.uti
l.Set 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.remov
e("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 foll
owing example shows how to compare two Set Collections.


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

/* Save with file name HashSetExample5.java */


import java.util.HashSet;

import java.util.Set;

import java.util.Arrays;

import java.util.Iterator;


public cla
ss HashSetExample5

{


public static void main(String args[])


{



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



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




//java.util.Set DECLARATION



Set s,

s2;




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



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



s2 = new HashSet(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));


}

}

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

27


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


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

/* Save with file name HashSetExample6.java */


import java.util.Hash
Set;

import java.util.Set;

import java.util.Arrays;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;


public class HashSetExample6

{


public static void main(String args[])


{



try



{




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





//java.util.Set DECLARATION




Set s;





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




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





//FileOutputStream CREATION




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





//ObjectOutputStream CREATION




ObjectOutputStream oos = new ObjectOutputStream(fos);





//WRITE Set OBJECT TO ObjectOutputStream




oos.writeObject(s);






//CLOSE THE ObjectOutputStream




oos.close();




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



}



catch(Exception e)



{




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



}


}

}


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


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

/* Save with f
ile name HashSetExample7.java */


import java.util.HashSet;

import java.util.Set;

import java.util.Arrays;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class HashSetExample7

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

28


{


public static void main(String args[])


{



try



{




//java.util.Set DECLARATION




Set s;





//FileInputStream CREATION




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





//ObjectInputStream CREATION




ObjectInputStream ois = new ObjectInputStream(fis);





//READ Set OBJECT FROM ObjectInpu
tStream




s = (Set) ois.readObject();




ois.close();




System.out.println(s);



}



catch(Exception e)



{




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



}


}

}


java.util.
TreeSet

Class


The other concrete Set implementation is the TreeS
et. The TreeSet class works exactly
the same as the HashSet class with one notable exception: instead of keeping its
elements unordered, a TreeSet keeps its elements ordered internally. Not only are the
elements ordered, but the tree is balanced. More spec
ifically, it's
a red−black tree.
Having a balanced tree guarantees a quick o(log n) search time at the cost of a more
time−intensive insertion (and deletion). Of course, elements added to the tree must be
orderable.


Red−black tree rules
:

1.

Every node in the tree is either

black or red.

2.

The root is always black.

3.

If a node is red, its children must be black.

4.

Every path from the root to a leaf (or null child) must contain the same number
of black nodes.


Because TreeSet implements the SortedSet interface as well as the Set in
terface,
understanding TreeSet is a little more involved than HashSet. HashSet

class has
following constructors.


In order to maintain an ordering, elements added to a tree set must provide some way
for the tree to order them. If the elements implement th
e Comparable interface, the first
constructor is sufficient. If, however, the objects aren't comparable or you don't like the
default ordering provided, you can pass along a custom Comparator to the constructor
that will be used to keep elements ordered. O
nce the TreeSet is created, you cannot
change the comparator.


TreeSet()

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

29


Constructs a new, empty tree set, sorted according to the natural ordering of its
elements.


TreeSet(Collection<? extends E> c)

Constructs a new tree set containing the elements in th
e specified collection, sorted
according to the natural ordering of its elements.


TreeSet(Comparator<? super E> comparator)

Constructs a new, empty tree set, sorted according to the specified comparator.


TreeSet(SortedSet<E> s)

Constructs a new tree set
containing the same elements and using the same ordering as
the specified sorted set.


In this tutorial you can learn about java.util.
TreeSet

class

and its examples
. And also
learn how to use java.util.
TreeSet

class.


/* java.util.TreeSet class Example */

/* Save with file name TreeSetExample.java */


import java.util.TreeSet;


public class TreeSetExample

{


public static void main(String args[])


{



//java.util.TreeSet DECLARATION



TreeSet ts;




//java.util.TreeSet OBJECT CREATION



//USING DEFAULT CONS
TRUCTOR



ts = new TreeSet();




//ADD AN ELEMENT



ts.add("Huda Tutorials");



ts.add("Java Tutorials");




//DUPLICATES NOT ALLOWED



ts.add("Huda Tutorials");



ts.add("C Tutorials");



ts.add("CPP Tutorials");




//RETURNS COUNT OF ELEMENTS TreeSet CON
TAINS



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




//java.util.TreeSet OUTPUT



System.out.println(ts);


}

}


The following example shows how to use TreeSet with Iterator.


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

/* Save with file name TreeSet
Example2.java */


import java.util.TreeSet;

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

30


import java.util.Iterator;


public class TreeSetExample2

{


public static void main(String args[])


{



//java.util.TreeSet DECLARATION



TreeSet ts;




//java.util.TreeSet OBJECT CREATION



//USING DEFAULT CONST
RUCTOR



ts = new TreeSet();




//ADD AN ELEMENT



ts.add("Huda Tutorials");



ts.add("Java Tutorials");




//DUPLICATES NOT ALLOWED



ts.add("Huda Tutorials");



ts.add("C Tutorials");



ts.add("CPP Tutorials");




//RETURNS COUNT OF ELEMENTS TreeSet CONT
AINS



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




//java.util.TreeSet OUTPUT



Iterator itr = ts.iterator();



while(itr.hasNext())



{




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



}


}

}


The following example shows how to use TreeSet with Arrays, Se
t and Iterator in
descending order.


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

/* Save with file name TreeSetExample3.java */


import java.util.TreeSet;

import java.util.Set;

import java.util.Arrays;

import java.util.Iterator;


public class TreeSetExample3

{


public static void main(String args[])


{



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



TreeSet ts; //java.util.TreeSet DECLARATION




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



//USING DEFAULT CONSTRUCTOR



ts = n
ew TreeSet(Arrays.asList(elements));




//java.util.TreeSet OUTPUT

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

31




Iterator itr = ts.descendingIterator();



while(itr.hasNext())



{




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



}


}

}


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

/* Save with file name TreeSetExamp
le4.java */


import java.util.TreeSet;

import java.util.Arrays;

import java.util.Iterator;


public class TreeSetExample4

{


public static void main(String args[])


{



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



TreeSet s; //ja
va.util.TreeSet DECLARATION




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



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




//ADD ELEMENT TO Set COLLECTION



s.add("NetBeans Tutorials");




//DISPLAY SIZE OF THE Set COLLECTION



System.out.printl
n("TreeSet Collection Size : "+s.size());




//CHECK THE Set COLLECTION IS EMPTY



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




//CHECK THE GIVEN ELEMENT IN Set COLLECTION



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




//RETURNS FIRST LOWEST ELEMENT



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




//RETURNS LAST ELEMENT



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




//java.util.Set 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 A
fter Element Remove");

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

32




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



itr = s.iterator();



while(itr.hasNext())



{




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



}


}

}


The following example shows how to compare two Set Collections.


/* java.util.TreeS
et class Example 5 */

/* Save with file name TreeSetExample5.java */


import java.util.TreeSet;

import java.util.Set;

import java.util.Arrays;

import java.util.Iterator;


public class TreeSetExample5

{


public static void main(String args[])


{



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



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




//java.util.TreeSet DECLARATION



Set s, s2;




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



//USING D
EFAULT CONSTRUCTOR



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



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




//COMPARE TWO COLLECTIONS



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




//CONTAINS COLLECTION IN OTHER COLLECTION



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


}

}


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


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

/* Save with file name TreeSetExample6.java */


import java.util.TreeSet;

import java.util.Set;

import java.u
til.Arrays;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;


public class TreeSetExample6

{


public static void main(String args[])


{

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

33




try



{




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





//java.
util.TreeSet DECLARATION




Set s;





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




//USING DEFAULT CONSTRUCTOR




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





//FileOutputStream CREATION




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





//ObjectOutputStream CREATION




ObjectOutputStream oos = new ObjectOutputStream(fos);





//WRITE Set OBJECT TO ObjectOutputStream




oos.writeObject(s);






//CLOSE THE ObjectOutputStream




oos.close();




System.out.println("Set Collection Saved

into File Sucessfully");



}



catch(Exception e)



{




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



}


}

}


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


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

/* Save with file n
ame TreeSetExample7.java */


import java.util.TreeSet;

import java.util.Set;

import java.util.Arrays;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class TreeSetExample7

{


public static void main(String args[])


{



try



{




//java.util.TreeSet DECLARATION




Set s;





//FileInputStream CREATION




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





//ObjectInputStream CREATION




ObjectInputStream ois = new ObjectInputStream(fis);


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

34





//READ Set OBJECT FROM ObjectInput
Stream




s = (Set) ois.readObject();




ois.close();




System.out.println(s);



}



catch(Exception e)



{




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



}


}

}


The following example shows how to create

a tree with a Comparator, filling
the tree,
and getting that comparator
.


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

/* Save with file name TreeSetExample8.java */


import java.util.TreeSet;

import java.util.Collections;


public class TreeSetExample8

{


public static void main(String args[])


{



//java.util.TreeSet DECLARATION



TreeSet ts;




//java.util.TreeSet OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



ts = new TreeSet(Collections.reverseOrder());




//ADD AN ELEMENT



ts.add("Huda Tutorials");



ts.add("Java Tutorials");



ts.add("C
Tutorials");



ts.add("CPP Tutorials");




//java.util.TreeSet OUTPUT



System.out.println(ts);




//java.util.TreeSet Comparator



System.out.println(ts.comparator());


}

}


j
ava.util.
HashMap Class


The HashMap is the most commonly used implementation of
the Map interface. It
provides a basic key−value

map where the elements are unordered. If you need to
maintain map keys in an ordered fashion, that's where

the TreeMap comes in handy
.


T
he

default

initial capacity of the internal data structure is

16

and t
he default load factor
is
0.75
.
Unlike a Hashtable, both the key and the value for a HashMap can be null. If the
key happens to already be in

the map, the old value is replaced and returned. Otherwise,
http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

35


null is returned. The map uses the key's hash code

to

determine where to store the
key−value pair internally.


Similar to the other collection classes, the
toString()
returned
value

will be a
comma−delimited list of the collection

elemen
ts within braces ({}). For the H
ash
M
ap,
each key−value element is displa
yed separated by an equal

sign.

The listed order does
not reflect the order in which the
elements are added to the HashM
ap. Instead, the order

reflects the range conversion of the hash codes generated from the keys.

Removing all
elements from a map does
not return the space used by the internal data structure. The

capacity of the structure remains the same. Only the entries of the structure are nulled
out.


HashMap

class has following constructors.


HashMap()

Constructs an empty HashMap with the default i
nitial capacity (16) and the default load
factor (0.75).


HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load
factor (0.75).


HashMap(int initialCapacity, float loadFactor)

Constructs an empty H
ashMap with the specified initial capacity and load factor.


HashMap(Map<? extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map.



/* java.util.HashMap class Example */

/* Save with file name HashMapExample.java */


import java.util.HashMap;

import java.util.Enumeration;


public class HashMapExample

{


public static void main(String args[])


{



//java.util.HashMap DECLARATION



HashMap<String,Integer> h;




//java.util.HashMap OBJECT CREATION



//USING DEFAULT CONS
TRUCTOR



h = new HashMap<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null KEY AND VALUE



h.put(null,null);




//HashMap OUTPUT



System.out.println
(h);

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

36



}

}


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

/* Save with file name HashMapExample2.java */


import java.util.HashMap;

import java.util.Iterator;

import java.util.Set;

import java.util.Collection;

import java.util.Iterator;


public class HashMapExamp
le2

{


public static void main(String args[])


{



//java.util.HashMap DECLARATION



HashMap<String,Integer> h;




//java.util.HashMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new HashMap<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE",
new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null KEY AND VALUE



h.put(null,null);




//HashMap KEYS OUTPUT



Set s = h.keySet();



Iterator itr = s.iterator();



int i=1;



while(itr.hasNext())



{




Syst
em.out.println("Key " + i++ + " : " + itr.next());



}




//HashMap VALUES OUTPUT



Collection c = h.values();



Iterator values = c.iterator();



int j=1;



while(values.hasNext())



{




System.out.println("Value " + j++ + " : " + values.next());



}


}

}


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

/* Save with file name HashMapExample3.java */


import java.util.HashMap;

import java.util.Map;

import java.util.Iterator;

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

37


import java.util.Set;

import java.util.Collection;

import java.util.Iterator;


public clas
s HashMapExample3

{


public static void main(String args[])


{



//java.util.HashMap DECLARATION



HashMap<String,Integer> h;




//java.util.HashMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new HashMap<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null KEY AND VALUE



h.put(null,null);




//HashMap KEYS OUTPUT



Set s = h.entrySet();



Iterator itr = s.iterator();



int i=1;



while(itr.hasNex
t())



{




//Map.Entry IS INNER INTERFACE OF Map INTERFACE




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




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



}


}

}


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

/* Save with file name HashMapExample4.jav
a */


import java.util.HashMap;

import java.util.Enumeration;


public class HashMapExample4

{


public static void main(String args[])


{



//java.util.HashMap DECLARATION



HashMap<String,Integer> h;




//java.util.HashMap OBJECT CREATION



//USING DEFAULT

CONSTRUCTOR



h = new HashMap<String,Integer>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

38





System.out.println("isEmpty : " + h.isEmpty());




//RETURNS THE NUMBER OF KEYS IN T
HIS HashMap



System.out.println("noof Keys : " + h.size());




System.out.println("Key ONE value : " + h.get("ONE"));




System.out.println("Contains key THREE : " + h.containsKey("THREE"));




System.out.println("Contains value 2 : " + h.containsValue(ne
w Integer(2)));


}

}


The following example shows how to save HashMap into file.


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

/* Save with file name HashMapExample5.java */


import java.util.HashMap;

import java.io.FileOutputStream;

import java.io.ObjectOutput
Stream;


public class HashMapExample5

{


public static void main(String args[])


{



try



{




//java.util.HashMap DECLARATION




HashMap<String,Integer> h;





//java.util.HashMap OBJECT CREATION




//USING DEFAULT CONSTRUCTOR




h = new HashMap<String,I
nteger>();





//ADD AN ELEMENTS




h.put("ONE", new Integer(1));




h.put("TWO", new Integer(2));




h.put("THREE", new Integer(3));





//FileOutputStream CREATION




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





//ObjectOutputStream CR
EATION




ObjectOutputStream oos = new ObjectOutputStream(fos);





//WRITE Set OBJECT TO ObjectOutputStream




oos.writeObject(h);






//CLOSE THE ObjectOutputStream




oos.close();




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



}



catc
h(Exception e)



{




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

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

39




}


}

}


The following example shows how to retrieve HashMap from file.


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

/* Save with file name HashMapExample6.java */


import java.ut
il.HashMap;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class HashMapExample6

{


public static void main(String args[])


{



try



{




//java.util.HashMap DECLARATION




HashMap<String,Integer> h;





//FileInputStream CREATI
ON




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





//ObjectInputStream CREATION




ObjectInputStream ois = new ObjectInputStream(fis);





//READ HashMap OBJECT FROM ObjectInputStream




h = (HashMap) ois.readObject();




ois.close();




S
ystem.out.println(h);



}



catch(Exception e)



{




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



}


}

}



j
ava.util.
TreeMap Class


A TreeMap is a map that maintains its keys ordered within a

balanced, red−black tree.

The map is sorted acc
ording to the natural ordering of its keys, or by a Comparator
provided at map creation time, depending on which constructor is used.


This implementation provides guaranteed log(n) time cost for the containsKey, get, put
and remove operations.

TreeMap

is

not synchronized. If multiple threads access a map
concurrently, and at least one of the threads modifies the map structurally, it must be
synchronized externally.


TreeMap

class has following constructors.


TreeMap()

Constructs a new, empty tree map, usi
ng the natural ordering of its keys.

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

40



TreeMap(Comparator<? super K> comparator)

Constructs a new, empty tree map, ordered according to the given comparator.


TreeMap(Map<? extends K,? extends V> m)

Constructs a new tree map containing the same mappings as
the given map, ordered
according to the natural ordering of its keys.


TreeMap(SortedMap<K,? extends V> m)

Constructs a new tree map containing the same mappings and using the same ordering
as the specified sorted map.


/* java.util.TreeMap class Example *
/

/* Save with file name TreeMapExample.java */


import java.util.TreeMap;

import java.util.Enumeration;


public class TreeMapExample

{


public static void main(String args[])


{



//java.util.TreeMap DECLARATION



TreeMap<String,Integer> h;




//java.util
.TreeMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new TreeMap<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null VALUE ONLY



h.put("FOUR",n
ull);




//TreeMap OUTPUT



System.out.println(h);


}

}


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

/* Save with file name TreeMapExample2.java */


import java.util.TreeMap;

import java.util.Iterator;

import java.util.Set;

import java.util.Collection;

import
java.util.Iterator;


public class TreeMapExample2

{


public static void main(String args[])


{



//java.util.TreeMap DECLARATION

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

41




TreeMap<String,Integer> h;




//java.util.TreeMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new TreeMap<String,Inte
ger>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null VALUE ONLY



h.put("FOUR",null);




//TreeMap KEYS OUTPUT



Set s = h.keySet();



Iterator itr = s.iterator();



int i=1;



while(itr.hasNext())



{




System.out.println("Key " + i++ + " : " + itr.next());



}




//TreeMap VALUES OUTPUT



Collection c = h.values();



Iterator values = c.iterator();



int j=1;



while(values.hasNext())



{




System.out.println("Va
lue " + j++ + " : " + values.next());



}


}

}


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

/* Save with file name TreeMapExample3.java */


import java.util.TreeMap;

import java.util.Map;

import java.util.Iterator;

import java.util.Set;

import java.util.Collec
tion;

import java.util.Iterator;


public class TreeMapExample3

{


public static void main(String args[])


{



//java.util.TreeMap DECLARATION



TreeMap<String,Integer> h;




//java.util.TreeMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new TreeMa
p<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

42




h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null VALUE ONLY



h.put("FOUR",null);




//TreeMap KEYS OUTPUT



Set s = h.entrySet();



Iterator itr =

s.iterator();



int i=1;



while(itr.hasNext())



{




//Map.Entry IS INNER INTERFACE OF Map INTERFACE




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




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



}


}

}


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

/* Save with file name TreeMapExample4.java */


import java.util.TreeMap;

import java.util.Enumeration;


public class TreeMapExample4

{


public static void main(String args[])


{



//java.util.TreeMap DECLARATION



TreeMap<String,Integer> h;




//java.ut
il.TreeMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new TreeMap<String,Integer>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




System.out.println("isEmpty : " + h.isEm
pty());




//RETURNS THE NUMBER OF KEYS IN THIS TreeMap



System.out.println("noof Keys : " + h.size());




System.out.println("Key ONE value : " + h.get("ONE"));




System.out.println("Contains key THREE : " + h.containsKey("THREE"));




System.out.printl
n("Contains value 2 : " + h.containsValue(new Integer(2)));


}

}


The following example shows how to save TreeMap into file.


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

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

43


/* Save with file name TreeMapExample5.java */


import java.util.TreeMap;

import java.io.F
ileOutputStream;

import java.io.ObjectOutputStream;


public class TreeMapExample5

{


public static void main(String args[])


{



try



{




//java.util.TreeMap DECLARATION




TreeMap<String,Integer> h;





//java.util.TreeMap OBJECT CREATION




//USING DEF
AULT CONSTRUCTOR




h = new TreeMap<String,Integer>();





//ADD AN ELEMENTS




h.put("ONE", new Integer(1));




h.put("TWO", new Integer(2));




h.put("THREE", new Integer(3));





//FileOutputStream CREATION




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





//ObjectOutputStream CREATION




ObjectOutputStream oos = new ObjectOutputStream(fos);





//WRITE Set OBJECT TO ObjectOutputStream




oos.writeObject(h);






//CLOSE THE ObjectOutputStream




oos.close();




System.out.println("TreeM
ap Saved into File Sucessfully");



}



catch(Exception e)



{




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



}


}

}


The following example shows how to retrieve TreeMap from file.


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

/* Save with file
name TreeMapExample6.java */


import java.util.TreeMap;

import java.io.FileInputStream;

import java.io.ObjectInputStream;


public class TreeMapExample6

{


public static void main(String args[])


{

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

44




try



{




//java.util.TreeMap DECLARATION




TreeMap<Str
ing,Integer> h;





//FileInputStream CREATION




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





//ObjectInputStream CREATION




ObjectInputStream ois = new ObjectInputStream(fis);





//READ TreeMap OBJECT FROM ObjectInputStream




h = (Tre
eMap) ois.readObject();




ois.close();




System.out.println(h);



}



catch(Exception e)



{




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



}


}

}



j
ava.util.
WeakHashMap Class


The WeakHashMap functions identically to the HashMap
.

I
f the

Java

memory manager no
longer has a strong reference to the object specified as a key, then the entry in the map

will be removed.

Both null values and the null key are supported.


WeakHashMap is not for caching. The idea is, suppose you have a bunch of o
bjects of a
certain class that you can't extend, but you want to associate some other piece of
information with each object. You can use a Map, with the main object as the key and
the extra info as the value. Using a WeakHashMap for this will make sure tha
t your Map
won't cause a memory leak, because it won't hold a strong reference to the main (key)
object; this will allow the object to be garbage collected when it's no longer needed.

W
hen the key is garbage collected, the value will soon be garbage coll
ected too, though
not immediately.


WeakHashMap

class has following constructors.


WeakHashMap()

Constructs a new, empty WeakHashMap with the default initial capacity (16) and load
factor (0.75).


WeakHashMap(int initialCapacity)

Constructs a new, empty We
akHashMap with the given initial capacity and the default
load factor (0.75).


WeakHashMap(int initialCapacity, float loadFactor)

Constructs a new, empty WeakHashMap with the given initial capacity and the given load
factor.


WeakHashMap(Map<? extends K,?
extends V> m)

Constructs a new WeakHashMap with the same mappings as the specified map.

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

45




/* java.util.WeakHashMap class Example */

/* Save with file name WeakHashMapExample.java */


import java.util.WeakHashMap;

import java.util.Enumeration;


public class

WeakHashMapExample

{


public static void main(String args[])


{



//java.util.WeakHashMap DECLARATION



WeakHashMap<String,Integer> h;




//java.util.WeakHashMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new WeakHashMap<String,Integer>();




//
Create a key for the map, keep the strong reference



String strongReference = new String("ONE");




//ADD KEY AND VALUE



h.put(strongReference, new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//WeakHashMap OUTPUT BEF
ORE null the strongReference



System.out.println(h);




strongReference = null;



//JAVA GARBAGE COLLECTION



System.gc();




//WeakHashMap OUTPUT AFTER null the strongReference



//AFTER null THE KEY THE ELEMENT IS REMOVED FROM Map



System.out.println(h
);


}

}


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

/* Save with file name WeakHashMapExample2.java */


import java.util.WeakHashMap;

import java.util.Iterator;

import java.util.Set;

import java.util.Collection;

import java.util.Iterator;


public class We
akHashMapExample2

{


public static void main(String args[])


{



//java.util.WeakHashMap DECLARATION



WeakHashMap<String,Integer> h;




//java.util.WeakHashMap OBJECT CREATION

http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

46




//USING DEFAULT CONSTRUCTOR



h = new WeakHashMap<String,Integer>();




//ADD

KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));




//ALLOW null KEY AND VALUE



h.put(null,null);




//WeakHashMap KEYS OUTPUT



Set s = h.keySet();



Iterator itr = s.iterator();



int i=1;



while(itr.hasNext())



{




System.out.println("Key " + i++ + " : " + itr.next());



}




//WeakHashMap VALUES OUTPUT



Collection c = h.values();



Iterator values = c.iterator();



int j=1;



while(values.hasNext())



{




System.out.println("Value " +

j++ + " : " + values.next());



}


}

}


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

/* Save with file name WeakHashMapExample3.java */


import java.util.WeakHashMap;

import java.util.Map;

import java.util.Iterator;

import java.util.Set;

import java.util.C
ollection;

import java.util.Iterator;


public class WeakHashMapExample3

{


public static void main(String args[])


{



//java.util.WeakHashMap DECLARATION



WeakHashMap<String,Integer> h;




//java.util.WeakHashMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new WeakHashMap<String,Integer>();




//ADD KEY AND VALUE



h.put("ONE", new Integer(1));



h.put("TWO", new Integer(2));



h.put("THREE", new Integer(3));


http://www.hudatutorials.com

Download lin
k:
http://www.hudatutorials.com/ht/java/util/
javacollectionsframework
.html

47




//ALLOW null KEY AND VALUE



h.put(null,null);




//WeakHashM
ap KEYS OUTPUT



Set s = h.entrySet();



Iterator itr = s.iterator();



int i=1;



while(itr.hasNext())



{




//Map.Entry IS INNER INTERFACE OF Map INTERFACE




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




System.out.println(entry.getKey()+" "+entry.getVa
lue());



}


}

}


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

/* Save with file name WeakHashMapExample4.java */


import java.util.WeakHashMap;

import java.util.Enumeration;


public class WeakHashMapExample4

{


public static void main(String args[])


{



//
java.util.WeakHashMap DECLARATION



WeakHashMap<String,Integer> h;




//java.util.WeakHashMap OBJECT CREATION



//USING DEFAULT CONSTRUCTOR



h = new WeakHashMap<String,Integer>();




//ADD AN ELEMENTS



h.put("ONE", new Integer(1));



h.put("TWO", new Int
eger(2));



h.put("THREE", new Integer(3));




System.out.println("isEmpty : " + h.isEmpty());




//RETURNS THE NUMBER OF KEYS IN THIS WeakHashMap



System.out.println("noof Keys : " + h.size());




System.out.println("Key ONE value : " + h.get("ONE"));




System.out.println("Contains key THREE : " + h.containsKey("THREE"));




System.out.println("Contains value 2 : " + h.containsValue(new Integer(2)));


}

}