Search the Web for JAVA Answers:

Search the Web for more JAVA Answers:
Hint: Press Ctrl+ to increase the font size of this blog and Ctrl- to decrease the font size of this blog.

JAVA Collections Answers



Introduction to Collections:
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. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).
Collection implementations in earlier versions of the Java platform included Vector, Hashtable, and array. However, those earlier versions did not contain a collections framework.


*Differentiate between Collection and Collections.
Collection is an interface and collections is a class.

Collection is the root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

The Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.


The following list describes the core collection interfaces:
-         Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements.
-         Set : A Set is a collection that cannot contain duplicate elements.
-         List :A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted. The user can access elements by their integer index (position) eg ArrayList.
-         Queue — a collection used to hold multiple elements prior to processing.
-         Map :A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value  eg HashMap.
----------------------------------------------------------------------------------

Quick Overview:

ArrayList class
This class uses dynamic arrays for storing elements, and arrays are sequentially arranged in the memory. It implements the List interface and extends the AbstractList class. It can contain duplicate elements, and it maintains an insertion order. The elements can be accessed using the index notation. This class contains various inbuilt methods, which help in making data retrieval and manipulation easy.




LinkedList class

This class uses a doubly-linked list to store elements. It maintains an insertion order, and it can be used as a list, stack or queue. It actually implements the List and Dequeue interfaces and extends the Abstract class. The add and remove methods are used to add and delete. The size method returns the number of lists in the list.



HashMap

This is used to store key value pairs. It implements the Map interface and is not a part of the collection. HashMap uses the hashing technique to store key value pairs. The key value pair is called a bucket. Each bucket is stored in an array in the HashMap class. The hashing function works on the key and returns an index at which the bucket is stored. There are chances of two keys returning the same index upon hashing. In such cases, the buckets are stored at the same index but are linked, the same as in a Linked List. Each bucket contains the pointer to the next bucket. The equals method is overridden, and the value is fetched when the key matches the key in the bucket. HashMap contains two basic methods, called get and put, to get the value and put the key value pair in the map.



TreeMap

The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a HashMap, a TreeMap guarantees that its elements will be sorted in ascending key order. You can specify the sorting order while creating TreeMap by providing an explicit ‘comparator’ to TreeMap. Basically, you can create TreeMap in Java in different ways—a TreeMap with a natural sorting order, and TreeMap with custom sorting order by providing the comparator, by copying the sorting order from the other SortedMap, etc.

TreeSet

This provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. It contains unique elements only.



----------------------------------------------------------------------------------
1. 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: i.e the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.
----------------------------------------------------------------------------------
2. What is HashMap and Map?

Map is Interface and Hashmap is class that implements this interface. Click Here for example.
----------------------------------------------------------------------------------
3. What is the significance of ListIterator? What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements.
----------------------------------------------------------------------------------
4. Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
----------------------------------------------------------------------------------
5. What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.
----------------------------------------------------------------------------------
6. Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.
----------------------------------------------------------------------------------
7. What is an Iterator interface?  What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.


Click Here on how to iterate a loop
----------------------------------------------------------------------------------
8. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
----------------------------------------------------------------------------------
9. What is the List interface?
The List interface provides support for ordered collections of objects.
----------------------------------------------------------------------------------
10. How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
----------------------------------------------------------------------------------
11. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
----------------------------------------------------------------------------------
12.What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.
----------------------------------------------------------------------------------
13.What is the Map interface?
The Map interface is used to associate keys with values.
----------------------------------------------------------------------------------
14. What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
----------------------------------------------------------------------------------
15. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector          b. ArrayList             c. LinkedList               
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
----------------------------------------------------------------------------------
16. How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). 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.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
----------------------------------------------------------------------------------
17. What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
----------------------------------------------------------------------------------
What is the difference between an Array, ArrayList and a List?

An Array (System.Array) is fixed in size once it is allocated. You can't add items to it or remove items from it. Also, all the elements must be the same type. As a result, it is type safe, and is also the most efficient of the three, both in terms of memory and performance. Also, System.Array supports multiple dimensions (i.e. it has a Rank property) while List and ArrayList do not (although you can create a List of Lists or an ArrayList of ArrayLists, if you want to).

An ArrayList is a flexible array which contains a list of objects. You can add and remove items from it and it automatically deals with allocating space. If you store value types in it, they are boxed and unboxed, which can be a bit inefficient. Also, it is not type-safe.

A List<> leverages generics; it is essentially a type-safe version of ArrayList. This means there is no boxing or unboxing (which improves performance) and if you attempt to add an item of the wrong type it'll generate a compile-time error.----------------------------------------------------------------------------------
18. What is difference between array and arraylist?

An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable.
Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive            ArrayList: Stores object only
Array: fix size                            ArrayList: resizable
Array: can have multi dimensional
Array: lang                                ArrayList: Collection framework
----------------------------------------------------------------------------------
19. Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity:
public vector(int initialcapacity)
----------------------------------------------------------------------------------
20. What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
----------------------------------------------------------------------------------
21. What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.
--------------------------------------------------
22. What is the difference between List and List (not parametrized list and list parametrized by String) in Java ?
List stores Objects so every "get" from List has to cast object to desired type.
List stores objects of type String only so casting is not necessary. Generalization gives compilation time error checking.
---------------------------------------------------------
23. Can you write your own generic types in Java ?
Yes.
---------------------------------------------------------
24. What is a Comparator?
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).
---------------------------------------------------------
25. Explain compareTo().

Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose.

It has this general form:                      int compareTo(String str)

Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here:

Value Meaning :
Less than zero- The invoking string is less than str.
Greater than zero- T he invoking string is greater than str.
Zero- The two strings are equal.
---------------------------------------------------------
26. Explain toString().
The toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object.


Example:
Class PointCoordinates {







private int x, y;
 public PointCoordinates(int x, int y) { this.x = x;this.y = y; }
 public int getX() { return x; }
 public int getY() { return y; }
 public String toString()  // Custom toString() Method.
{  return "X=" + x + " " + "Y=" + y; }
}
public class ToStringDemo2 {
 public static void main(String args[]) {
  PointCoordinates point = new PointCoordinates(10, 10);
  System.out.println(point);
  String s = point + " testing";
  System.out.println(s); }}

27.Why use an ArrayList instead of a Vector? 
All methods of the Vector class are synchronized. It is safe to access a Vector object from two threads. But if you only access a vector from a single thread—by far the more common case—your code wastes quite a bit of time with synchronization. In contrast, the ArrayList methods are not synchronized. We recommend that you use an ArrayList instead of a Vector whenever you don't need synchronization.