Collections in Java
HashMap:
--------
hashCode() method is used to get the hash code of the object.
In HashMap, hashCode() is used to calculate the bucket.
Bucket - used to store nodes. 2 or more nodes can have same bucket. Those nodes are linked via linked list.
index of bucket = hashCode(key) & (n-1)
n=size of bucket array
HashMap hm = new HashMap();
hm.put("a",1);
First, hashCode of key 'a' is calculated and then the index of bucket array.
Second, the details of element is stored as a linked list.
{
int hash = 115
Key key = {"saurabh"}
Integer value = 30
Node next = null
}
Third, in case of same index the new element is saved as an linked list with address saved on next variable of first element.
Collection:
----------
1. Iterable Interface: Root interface of all collection class.
it contains only one abstract method i.e., Iterator<T> iterator()
2. Collection Interface : implemented by all class in collection framework.
Declares the method that every collection will have. eg., Boolean add(Object obj), boolean addAll(Collection c), void clear()
3. List Interface : Ordered collection of object. duplicacy allowed
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
list1.add("a")
Iterator i = list1.iterator();
while(i.hasNext()){
sop(i.next());
}
Stack is a subclass of Vector. It implements LIFO.
few methods: Boolean push(), Boolean peek() - it returns the first element ie., head of stack ---- In stack the head element is the last element.
4. Queue: its a interface which maintains the first in first out order. It is an ordered list. classes which implements Queue are PriorityQueue, Deque, Arraydeque.
5. Set: unordered set of elements with no duplicacy. can store 1 null.
Set<data-type> s1 = new HashSet<data-type>();
-non synchronized means multiple thread cant use the same object efficiently
-doesnt maintain insertion order
-Best for searching operation
Set<data-type> s2 = new LinkedHashSet<data-type>();
-non synchronized
-Maintains insertion order
Set<data-type> s3 = new TreeSet<data-type>();
-Access and retrieval is fast
-not allow null
-non synchronized
-ascending order i.e., sorted order
6. Map: Interface
HashMap - it doesn't maintain any order.
LinkedHashMap - It maintains insertion order.
TreeMap - It maintains ascending order.
7. Collections.sort(al,Collections.reverseOrder());
Comments
Post a Comment