Getting Started with Java Collection Framework
If you want to write a program that collects objects, you have a number of choices. Of course, you can use an array list, but computer scientists have invented other mechanisms that may be better suited for the task. When you need to organize multiple objects in your program, you can place them into a collection.
What is Collection?
Collection is the group of Object references in Java. It is created using data structures. It may be ordered or unordered, may have duplicate entries, depends upon the sub-types we use.
Hierarchy of Collection Framework.
Interfaces in Collection Framework
- Lists
- Sets
- Queue
- Map
Lists:
You use a list whenever you want to retain the order that you established. For example, on your bookshelf, you may order books by topic. A list is an appropriate data structure for such a collection because the ordering matters to you.
Sets:
In many applications, you don’t really care about the order of the elements in a collection. Consider a mail-order dealer of books. Without customers browsing the shelves, there is no need to order books by topic. Such a collection without an intrinsic order is called a set.
Queues:
In a queue, you add items to one end (the tail) and remove them from the other end (the head). For example, you could keep a queue of books, adding required reading at the tail and taking a book from the head whenever you have time to read another one.
Maps:
A map manages associations between keys and values. Every key in the map has an associated value. The map stores the keys, values, and the associations between them. For an example, consider a library that puts a bar code on each book. The program used to check books in and out needs to look up the book associated with each bar code. A map associating bar codes with books can solve this problem.
Types of Lists in Collection Framework
- Array-List
- Stack
- Linked-List
Working with Array-List.
- In Array-List we can insert an object at a specific position with replacing or without replacing the element.
- We can remove the specific element with the index or name. If we used the name of an object to remove all the objects of the specific elements will remove as Array-List supports repetition of the object with a name.
Working with Linked-List.
- A linked list is a data structure used for collecting a sequence of objects that allows efficient addition and removal of elements in the middle of the sequence.
- It is a generic class, just like the Array-List class.
Linked list uses a sequence of nodes. A node is an object that stores an element and references to the neighboring nodes in the sequence.
When you insert a new node into a linked list, only the neighboring node references need to be updated.
The same is true when you remove a node. Linked lists allow efficient insertion and removal, but element access can be inefficient.
Pros.
- Adding and removing elements at a given location in a linked list is efficient.
- Visiting the elements of a linked list in sequential order is efficient.
Cons.
- Random Access to any element in linked-list is not efficient.
Working with Stack.
- A stack lets you insert and remove elements only at one end, traditionally called the top of the stack.
- New items can be added to the top of the stack. Items are removed from the top of the stack as well. Therefore, they are removed in the order that is opposite from the order in which they have been added, called last-in, first-out or LIFO order.
Examples
Consider the undo feature of a word processor. It keeps the issued commands in a stack. When you select “Undo”, the last command is undone, then the next-to-last, and so on.Another important example is the run-time stack that a processor or virtual machine keeps to store the values of variables in nested methods. Whenever a new method is called, its parameter variables and local variables are pushed onto a stack. When the method exits, they are popped off again.
Working with Queue.
- A queue lets you add items to one end of the queue (the tail) and remove them from the other end of the queue (the head). Queues yield items in a first-in, first-out or FIFO fashion. Items are removed in the same order in which they were added. A typical application is a print queue.
- The Queue interface in the standard Java library has methods add to add an element to the tail of the queue, remove to remove the head of the queue, and peek to get the head element of the queue without removing it.
- The Linked-List class implements the Queue interface. Whenever you need a queue, simply initialize a Queue variable with a Linked-List object.
Working with Priority Queue.
- Priority queue collects elements, each of which has a priority. A typical example of a priority queue is a collection of work requests, some of which may be more urgent than others. Unlike a regular queue, the priority queue does not maintain a first-in, first-out discipline. Instead, elements are retrieved according to their priority. In other words, new items can be inserted in any order. But whenever an item is removed, it is the item with the most urgent priority.
- It is customary to give low values to urgent priorities, with priority 1 denoting the most urgent priority. Thus, each removal operation extracts the minimum element from the queue.
Working with Hash-Set and Tree-Set.
- The Hash-Set and Tree-Set classes implement the Set interface.
- Hash-Set is implemented using hash table and Tree-Set is implemented using Binary Search Tree.
- In order to use a hash table, the elements must have a method to compute those integer values. This method is called hash-Code. The elements must also belong to a class with a properly defined equals method. Suppose you want to form a set of elements belonging to a class that you declared, such as a HashSet<Book>. Then you need to provide hash-Code and equals methods for the class Book. There is one exception to this rule. If all elements are distinct (for example, if your program never has two Book objects with the same author and title), then you can simply inherit the hash-Code and equals methods of the Object class.
- In Tree-Set, elements are kept in sorted order. For example, a set of books might be arranged by height, or alphabetically by author and title. The elements are not stored in an array — that would make adding and removing elements too inefficient. Instead, they are stored in nodes, as in a linked list. However, the nodes are not arranged in a linear sequence but in a tree shape.
- You should choose a Tree-Set if you want to visit the set’s elements in sorted order. Otherwise choose a Hash-Set — as long as the hash function is well chosen, it is a bit more efficient.
When you construct a Hash-Set or Tree-Set, store the reference in a Set<String> variable, either as
Set<String> names = new HashSet<String>();
or
Set<String> names = new TreeSet<String>();
After you construct the collection object, the implementation no longer matters; only the interface is important.
Working with Maps.
A map allows you to associate elements from a key set with elements from a value collection. You use a map when you want to look up objects by using a key.
The Java library has two implementations for the Map interface: Hash-Map and Tree-Map.
After constructing a Hash-Map or Tree-Map, you can store the reference to the map object in a Map reference:
Map<String, Color> favoriteColors = new HashMap<String, Color>();
Use the put method to add an association:
favoriteColors.put(“Juliet”, Color.RED);
You can change the value of an existing association, simply by calling put again:
favoriteColors.put(“Juliet”, Color.BLUE);
The get method returns the value associated with a key. Color julietsFavoriteColor = favoriteColors.get(“Juliet”);
If you ask for a key that isn’t associated with any values, then the get method returns null.To remove an association, call the remove method with the key:
favoriteColors.remove(“Juliet”);