Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html Java Collections Framework A collection sometimes called a container is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collection is the same as the intuitive, mathematical concept of a set. A set is just a group of unique items, meaning that the group contains no duplicates. Java Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. The framework provides a convenient API to many of the abstract data types maps, sets, lists, trees, arrays, hashtables, and other collections. Because of their object-oriented design, the Java classes in the Collections Framework encapsulate both the data structures and the algorithms associated with these abstractions. With the Java Collections Framework the programmer easily define higher level data abstractions, such as stacks, queues, and thread safe collections. You should be able to understand the Collections Framework more easily. The Collections Framework is made up of a set of interfaces for working with groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. The following diagrams shows the framework interface hierarchy. What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy. Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures. Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. 1 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html Benefits of the Java Collections Framework The Java Collections Framework provides the following benefits: 1. Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs. 2. Increases program speed and quality: The Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance. 3. Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, APIs will interoperate seamlessly, even though they were written independently. 4. Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away. 5. Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces. 6. Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces. The Java Collections Framework consists of following classes, interfaces and utility classes. Collection Classes AbstractCollection AbstractList AbstractMap AbstractQueue AbstractSequentialList AbstractSet ArrayDeque ArrayList Arrays Collections EnumMap EnumSet HashMap HashSet Hashtable IdentityHashMap LinkedHashMap LinkedHashSet 2 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html LinkedList PriorityQueue TreeMap TreeSet Vector WeakHashMap Collection Interfaces Collection Set List Queue Deque Map SortedSet SortedMap NavigableSet NavigableMap BlockingQueue BlockingDeque ConcurrentMap ConcurrentNavigableMap java.util.Arrays Class This class contains various methods for manipulating arrays (such as sorting and searching). This class contains a static factory that allows arrays to be viewed as lists. You need not to instantiate java.util.Arrays class because all the methods are static methods so that we can call the methods with the class name. The methods in this class all throw a NullPointerException if the specified array reference is null, except where noted. In this tutorial you can learn about java.util.Arrays class and its examples. And also learn how to use java.util.Arrays class. Following example shows how to use int array with java.util.Arrays class. /* java.util.Arrays class Example */ /* Save with file name ArraysExample.java */ import java.util.Arrays; public class ArraysExample { public static void main(String args[]) { //int ARRAY DECLARATION AND CREATION int arr[] = {0,-5,2,5,-1,-4,-3,-2,3,1,4}; //int ARRAY OUTPUT AS STRING System.out.println(Arrays.toString(arr)); //int ARRAY SORTING Arrays.sort(arr); 3 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //int ARRAY OUTPUT AS STRING AFTER SORTING System.out.println("After Sorting"); System.out.println(Arrays.toString(arr)); //SEARCHING IN int ARRAY int index = Arrays.binarySearch(arr, 3); if( index >= 0 ) System.out.println("3 is Found at Index : " + index); else System.out.println("3 is NOT Found"); //FILLING int ARRAY WITH DEFAULT ZERO Arrays.fill(arr,0); //int ARRAY OUTPUT AFTER FILL System.out.println(Arrays.toString(arr)); } } Following example shows how to use double array with java.util.Arrays class. /* java.util.Arrays class Example 2 */ /* Save with file name ArraysExample2.java */ import java.util.Arrays; public class ArraysExample2 { public static void main(String args[]) { //double ARRAY DECLARATION AND CREATION double arr[] = {0.0,-5.0,2.0,5.0,-1.5,-4.0,-3.0,-2.0,3.0,1.5,4.0}; //double ARRAY OUTPUT AS STRING System.out.println(Arrays.toString(arr)); //double ARRAY SORTING Arrays.sort(arr); //double ARRAY OUTPUT AS STRING AFTER SORTING System.out.println("After Sorting"); System.out.println(Arrays.toString(arr)); //SEARCHING IN double ARRAY int index = Arrays.binarySearch(arr, 3); if( index >= 0 ) System.out.println("3 is Found at Index : " + index); else System.out.println("3 is NOT Found"); //FILLING double ARRAY WITH DEFAULT ZERO Arrays.fill(arr,0); //double ARRAY OUTPUT AFTER FILL System.out.println(Arrays.toString(arr)); } 4 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html } Note: When filling an object array, the fill() method will copy the same object reference to every cell in the array. After filling the array, if you then change that one reference, the attributes of the object in every cell in the array will be changed. Following example shows how to use String array with java.util.Arrays class. /* java.util.Arrays class Example 3 */ /* Save with file name ArraysExample3.java */ import java.util.Arrays; import java.util.Collections; public class ArraysExample3 { public static void main(String args[]) { //String ARRAY DECLARATION AND CREATION String arr[] = {"Java Tutorials","NetBeans Tutorials","Huda Tutorials","C"}; //String ARRAY OUTPUT AS STRING for(int i=0; i < arr.length; i++) { System.out.println(arr[i]); } //String ARRAY SORTING Arrays.sort(arr); //String ARRAY OUTPUT AS STRING AFTER SORTING System.out.println("\nAfter Sorting\n"); for(int i=0; i < arr.length; i++) { System.out.println(arr[i]); } //SEARCHING IN String ARRAY int index = Arrays.binarySearch(arr, "Huda Tutorials"); if( index >= 0 ) System.out.println("\nHuda Tutorials is Found at Index : " + index); else System.out.println("\nHuda Tutorials is NOT Found"); //String ARRAY REVERSE ORDER Arrays.sort(arr,Collections.reverseOrder()); //String ARRAY OUTPUT AS STRING AFTER SORTING System.out.println("\nAfter Reverse Order\n"); for(int i=0; i < arr.length; i++) { System.out.println(arr[i]); } //FILLING String ARRAY WITH DEFAULT null Arrays.fill(arr,null); 5 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //String ARRAY OUTPUT AFTER FILL System.out.println(Arrays.toString(arr)); } } java.util.ArrayList Class The ArrayList class is the Collection Framework's replacement for the Vector class. Functionally equivalent, their primary difference is that ArrayList usage is not synchronized by default, whereas Vector is. Both maintain their collection of data in an ordered fashion within an array as their backing store. Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The array provides quick, random access to elements at a cost of slower insertion and deletion of those elements not at the end of the list. If you need to frequently add and delete elements from the middle of the list, consider using a LinkedList. ArrayList shares some similarities with HashSet and TreeSet and provides some behavior that is not the same. The base implementation class is similar to HashSet and TreeSet both extend from the AbstractCollection superclass. However, instead of further extending from AbstractSet, ArrayList extends from AbstractList. Unlike the sets, ArrayList supports storing duplicate elements. While much of the ArrayList behavior is inherited from AbstractList, the class still needs to customize the majority of its behavior. ArrayList class has following constructors. ArrayList() Constructs an empty list with an initial capacity of ten. ArrayList(Collection<? extends E> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. ArrayList(int initialCapacity) Constructs an empty list with the specified initial capacity. In this tutorial you can learn about java.util.ArrayList class and its examples. And also learn how to use java.util.ArrayList class. /* java.util.ArrayList class Example */ /* Save with file name ArrayListExample.java */ import java.util.ArrayList; public class ArrayListExample { public static void main(String args[]) { 6 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //java.util.ArrayList DECLARATION ArrayList al; //java.util.ArrayList OBJECT CREATION //USING DEFAULT CONSTRUCTOR al = new ArrayList(); //ADD AN ELEMENT al.add("Huda Tutorials"); al.add("Java Tutorials"); //DUPLICATES ARE ALLOWED al.add("Huda Tutorials"); al.add("C Tutorials"); al.add("CPP Tutorials"); //null ALLOWED al.add(null); //RETURNS COUNT OF ELEMENTS ArrayList CONTAINS System.out.println("Elements Count : " + al.size()); //java.util.ArrayList OUTPUT System.out.println(al); } } The following example shows how to use ArrayList with Iterator. /* java.util.ArrayList class Example 2 */ /* Save with file name ArrayListExample2.java */ import java.util.ArrayList; import java.util.Iterator; public class ArrayListExample2 { public static void main(String args[]) { //java.util.ArrayList DECLARATION ArrayList al; //java.util.ArrayList OBJECT CREATION //USING DEFAULT CONSTRUCTOR al = new ArrayList(); //ADD AN ELEMENT al.add("Huda Tutorials"); al.add("Java Tutorials"); //DUPLICATES ARE ALLOWED al.add("Huda Tutorials"); al.add("C Tutorials"); al.add("CPP Tutorials"); //null ALLOWED al.add(null); 7 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 import import import java.util.ArrayList; java.util.List; java.util.Arrays; 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 import import import java.util.ArrayList; java.util.List; java.util.Arrays; 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 8 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //java.util.List OBJECT CREATION USING ARRAY AS LIST s = new ArrayList(Arrays.asList(elements)); //ADD ELEMENT TO List COLLECTION s.add("NetBeans Tutorials"); //DISPLAY SIZE OF THE List COLLECTION System.out.println("List Collection Size : "+s.size()); //CHECK THE List COLLECTION IS EMPTY System.out.println("List Collection is Empty : "+s.isEmpty()); //CHECK THE GIVEN ELEMENT IN List COLLECTION System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials")); //java.util.List OUTPUT System.out.println(); System.out.println("Elements Before Element Remove"); System.out.println("------------------------------"); Iterator itr = s.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } s.remove("C Tutorials"); System.out.println(); System.out.println("Elements After Element Remove"); System.out.println("------------------------------"); itr = s.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } } The following example shows how to compare two List Collections. /* java.util.ArrayList class Example 5 */ /* Save with file name ArrayListExample5.java */ import import import import java.util.ArrayList; java.util.List; java.util.Arrays; java.util.Iterator; public class ArrayListExample5 { public static void main(String args[]) { String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"}; String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"}; //java.util.List DECLARATION List s, s2; 9 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 import import import import java.util.ArrayList; java.util.List; java.util.Arrays; java.io.FileOutputStream; java.io.ObjectOutputStream; public class ArrayListExample6 { public static void main(String args[]) { try { String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"}; //java.util.ArrayList DECLARATION List s; //java.util.List OBJECT CREATION USING ARRAY AS LIST s = new ArrayList(Arrays.asList(elements)); //FileOutputStream CREATION FileOutputStream fos = new FileOutputStream("List.set"); //ObjectOutputStream CREATION ObjectOutputStream oos = new ObjectOutputStream(fos); //WRITE List OBJECT TO ObjectOutputStream oos.writeObject(s); //CLOSE THE ObjectOutputStream oos.close(); System.out.println("List Collection Saved into File Sucessfully"); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } } 10 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html The following example shows how to retrieve List Collection from file. /* java.util.ArrayList class Example 7 */ /* Save with file name ArrayListExample7.java */ import import import import import java.util.ArrayList; java.util.List; java.util.Arrays; java.io.FileInputStream; java.io.ObjectInputStream; public class ArrayListExample7 { public static void main(String args[]) { try { //java.util.ArrayList DECLARATION List s; //FileInputStream CREATION FileInputStream fis = new FileInputStream("List.set"); //ObjectInputStream CREATION ObjectInputStream ois = new ObjectInputStream(fis); //READ List OBJECT FROM ObjectInputStream s = (List) ois.readObject(); ois.close(); System.out.println(s); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } } The following example shows how to use ArrayList with Arrays, List and ListIterator. /* java.util.ArrayList class Example 8 */ /* Save with file name ArrayListExample8.java */ import import import import java.util.ArrayList; java.util.List; java.util.Arrays; java.util.ListIterator; public class ArrayListExample8 { public static void main(String args[]) { String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"}; List s; //java.util.List DECLARATION //java.util.List OBJECT CREATION USING ARRAY AS LIST s = new ArrayList(Arrays.asList(elements)); 11 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 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. Linked 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 stack 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 structurally 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 an 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 its 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 { 12 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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("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 LinkedList CONTAINS System.out.println("Elements Count : " + al.size()); //java.util.LinkedList OUTPUT 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; public 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("Huda Tutorials"); al.add("Java Tutorials"); //DUPLICATES ARE ALLOWED al.add("Huda Tutorials"); al.add("C Tutorials"); al.add("CPP Tutorials"); 13 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //null ALLOWED al.add(null); //RETURNS COUNT OF ELEMENTS LinkedList CONTAINS System.out.println("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 import import import java.util.LinkedList; java.util.List; java.util.Arrays; java.util.Iterator; public class LinkedListExample3 { 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 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 import import import java.util.LinkedList; java.util.List; java.util.Arrays; java.util.Iterator; public class LinkedListExample4 { public static void main(String args[]) { String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"}; 14 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 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.LinkedList class Example 5 */ /* Save with file name LinkedListExample5.java */ import import import import java.util.LinkedList; java.util.List; java.util.Arrays; java.util.Iterator; public class LinkedListExample5 { public static void main(String args[]) { String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"}; String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"}; 15 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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)); //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.LinkedList class Example 6 */ /* Save with file name LinkedListExample6.java */ import import import import import java.util.LinkedList; java.util.List; java.util.Arrays; java.io.FileOutputStream; 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 FileOutputStream fos = new FileOutputStream("List.set"); //ObjectOutputStream CREATION ObjectOutputStream oos = new ObjectOutputStream(fos); //WRITE List OBJECT TO ObjectOutputStream oos.writeObject(s); //CLOSE THE ObjectOutputStream oos.close(); System.out.println("List Collection Saved into File Sucessfully"); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } 16 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html } The following example shows how to retrieve List Collection from file. /* java.util.LinkedList class Example 7 */ /* Save with file name LinkedListExample7.java */ import import import import import java.util.LinkedList; java.util.List; java.util.Arrays; java.io.FileInputStream; java.io.ObjectInputStream; public class LinkedListExample7 { public static void main(String args[]) { try { //java.util.LinkedList DECLARATION List s; //FileInputStream CREATION FileInputStream fis = new FileInputStream("List.set"); //ObjectInputStream CREATION ObjectInputStream ois = new ObjectInputStream(fis); //READ List OBJECT FROM ObjectInputStream s = (List) ois.readObject(); ois.close(); System.out.println(s); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } } The following example shows how to use LinkedList with Arrays, Iterator and ListIterator. /* java.util.LinkedList class Example 8 */ /* Save with file name LinkedListExample8.java */ import import import import java.util.LinkedList; java.util.Arrays; java.util.ListIterator; 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 17 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //java.util.List 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 Example 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 CREATION //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 Tutorials2"); //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()); 18 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //GET THE LAST ELEMENT System.out.println("Last Element : " + al.getLast()); //GET THE HEAD (FIRST) ELEMENT System.out.println("Head (First) Element : " + al.peek()); } } java.util.Hashtable Class A Hashtable is a specialized Dictionary that relies on a hashing algorithm to convert keys into a mechanism 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 the 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 at 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 get 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 default 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 capacity 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 its 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 automatic 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(String args[]) { //java.util.Hashtable DECLARATION Hashtable<String,Integer> h; //java.util.Hashtable OBJECT CREATION 19 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 OUTPUT Enumeration e = h.elements(); while(e.hasMoreElements()) { System.out.println(e.nextElement()); } } } /* java.util.Hashtable class Example 2 */ /* Save with file name HashtableExample2.java */ import import import import java.util.Hashtable; java.util.Enumeration; java.util.Collection; 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.iterator(); int j=1; while(values.hasNext()) { System.out.println("Value " + j++ + " : " + values.next()); } 20 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html } } /* 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,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.isEmpty()); //RETURNS THE NUMBER OF KEYS IN THIS Hashtable 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.contains (new Integer(2))); } } The following example 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 HashtableExample4 { public static void main(String args[]) { try { //java.util.Hashtable DECLARATION Hashtable<String,Integer> h; //java.util.Hashtable OBJECT CREATION 21 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 ObjectOutputStream 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); } 22 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 HashSet 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 containing 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) Constructs 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 OBJECT CREATION //USING DEFAULT CONSTRUCTOR hs = new HashSet(); 23 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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"); //RETURNS 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 OBJECT 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"); //RETURNS 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()); } } } 24 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html The following example shows how to use HashSet with Arrays, Set and Iterator. /* java.util.HashSet class Example 3 */ /* Save with file name HashSetExample3.java */ import import import import java.util.HashSet; java.util.Set; java.util.Arrays; java.util.Iterator; public class HashSetExample3 { 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 import import import java.util.HashSet; java.util.Set; java.util.Arrays; 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 DECLARATION //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()); 25 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //CHECK THE GIVEN ELEMENT IN Set COLLECTION System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials")); //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 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 Set Collections. /* java.util.HashSet class Example 5 */ /* Save with file name HashSetExample5.java */ import import import import java.util.HashSet; java.util.Set; java.util.Arrays; java.util.Iterator; public class 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)); } } 26 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html The following example shows how to save Set Collection into file. /* java.util.HashSet class Example 6 */ /* Save with file name HashSetExample6.java */ import import import import import java.util.HashSet; java.util.Set; java.util.Arrays; java.io.FileOutputStream; java.io.ObjectOutputStream; public class HashSetExample6 { public static void main(String args[]) { try { String elements[] = {"Huda Tutorials","Java Tutorials","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 file name HashSetExample7.java */ import import import import import java.util.HashSet; java.util.Set; java.util.Arrays; java.io.FileInputStream; java.io.ObjectInputStream; public class HashSetExample7 27 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html { 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 ObjectInputStream 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 TreeSet. 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 specifically, 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 interface, 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 the 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. Once the TreeSet is created, you cannot change the comparator. TreeSet() 28 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 the 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 CONSTRUCTOR 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 CONTAINS 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 TreeSetExample2.java */ import java.util.TreeSet; 29 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 CONSTRUCTOR 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 CONTAINS 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, Set and Iterator in descending order. /* java.util.TreeSet class Example 3 */ /* Save with file name TreeSetExample3.java */ import import import import java.util.TreeSet; java.util.Set; java.util.Arrays; 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 = new TreeSet(Arrays.asList(elements)); //java.util.TreeSet OUTPUT 30 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html Iterator itr = ts.descendingIterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } } /* java.util.TreeSet class Example 4 */ /* Save with file name TreeSetExample4.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; //java.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.println("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.contains("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 After Element Remove"); 31 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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.TreeSet class Example 5 */ /* Save with file name TreeSetExample5.java */ import import import import java.util.TreeSet; java.util.Set; java.util.Arrays; java.util.Iterator; public class TreeSetExample5 { public static void main(String args[]) { String elements[] = {"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 DEFAULT 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("Contains : " + 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 import import import import java.util.TreeSet; java.util.Set; java.util.Arrays; java.io.FileOutputStream; java.io.ObjectOutputStream; public class TreeSetExample6 { public static void main(String args[]) { 32 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 name TreeSetExample7.java */ import import import import import java.util.TreeSet; java.util.Set; java.util.Arrays; java.io.FileInputStream; 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); 33 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //READ Set OBJECT FROM ObjectInputStream 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()); } } java.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. The default initial capacity of the internal data structure is 16 and the 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, 34 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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 elements within braces ({}). For the HashMap, each key−value element is displayed separated by an equal sign. The listed order does not reflect the order in which the elements are added to the HashMap. 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 initial 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 HashMap 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 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 OUTPUT System.out.println(h); 35 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html } } /* java.util.HashMap class Example 2 */ /* Save with file name HashMapExample2.java */ import import import import import java.util.HashMap; java.util.Iterator; java.util.Set; java.util.Collection; java.util.Iterator; public class HashMapExample2 { 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()) { System.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; 36 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html import java.util.Set; import java.util.Collection; import java.util.Iterator; public class 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.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.HashMap class Example 4*/ /* Save with file name HashMapExample4.java */ 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)); 37 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html System.out.println("isEmpty : " + h.isEmpty()); //RETURNS THE NUMBER OF KEYS IN THIS 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(new 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.ObjectOutputStream; 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,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("hashmap.set"); //ObjectOutputStream CREATION 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"); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); 38 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html } } } The following example shows how to retrieve HashMap from file. /* java.util.HashMap class Example 6 */ /* Save with file name HashMapExample6.java */ import java.util.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 CREATION FileInputStream fis = new FileInputStream("hashmap.set"); //ObjectInputStream CREATION ObjectInputStream ois = new ObjectInputStream(fis); //READ HashMap OBJECT FROM ObjectInputStream h = (HashMap) ois.readObject(); ois.close(); System.out.println(h); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } } java.util.TreeMap Class A TreeMap is a map that maintains its keys ordered within a balanced, red−black tree. The map is sorted according 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, using the natural ordering of its keys. 39 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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",null); //TreeMap OUTPUT System.out.println(h); } } /* java.util.TreeMap class Example 2 */ /* Save with file name TreeMapExample2.java */ import import import import import java.util.TreeMap; java.util.Iterator; java.util.Set; java.util.Collection; java.util.Iterator; public class TreeMapExample2 { public static void main(String args[]) { //java.util.TreeMap DECLARATION 40 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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",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("Value " + j++ + " : " + values.next()); } } } /* java.util.TreeMap class Example 3 */ /* Save with file name TreeMapExample3.java */ import import import import import import java.util.TreeMap; java.util.Map; java.util.Iterator; java.util.Set; java.util.Collection; 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 TreeMap<String,Integer>(); //ADD KEY AND VALUE h.put("ONE", new Integer(1)); 41 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html 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.util.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.isEmpty()); //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.println("Contains value 2 : " + h.containsValue(new Integer(2))); } } The following example shows how to save TreeMap into file. /* java.util.TreeMap class Example 5 */ 42 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html /* Save with file name TreeMapExample5.java */ import java.util.TreeMap; import java.io.FileOutputStream; 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 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)); //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("TreeMap 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[]) { 43 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html try { //java.util.TreeMap DECLARATION TreeMap<String,Integer> h; //FileInputStream CREATION FileInputStream fis = new FileInputStream("treemap.set"); //ObjectInputStream CREATION ObjectInputStream ois = new ObjectInputStream(fis); //READ TreeMap OBJECT FROM ObjectInputStream h = (TreeMap) ois.readObject(); ois.close(); System.out.println(h); } catch(Exception e) { System.out.println("Error Occurred : " + e.getMessage()); } } } java.util.WeakHashMap Class The WeakHashMap functions identically to the HashMap. If 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 objects 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 that 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. When the key is garbage collected, the value will soon be garbage collected 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 WeakHashMap 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. 44 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html /* 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 BEFORE 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 import import import import java.util.WeakHashMap; java.util.Iterator; java.util.Set; java.util.Collection; java.util.Iterator; public class WeakHashMapExample2 { public static void main(String args[]) { //java.util.WeakHashMap DECLARATION WeakHashMap<String,Integer> h; //java.util.WeakHashMap OBJECT CREATION 45 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //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 import import import import import java.util.WeakHashMap; java.util.Map; java.util.Iterator; java.util.Set; java.util.Collection; 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)); 46 http://www.hudatutorials.com Download link: http://www.hudatutorials.com/ht/java/util/javacollectionsframework.html //ALLOW null KEY AND VALUE h.put(null,null); //WeakHashMap 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.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 Integer(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))); } } 47