Sei sulla pagina 1di 30

Iterable

Iterator

Map.Entry

AbstractCollection

Collection

ListIterator

List

SortedSet

AbstractList

Dictionary

Map

Set

AbstractSet

SortedMap

AbstractMap

Hashtable

Properties

AbstractSeq
uentialList

LinkedList

ArrayList

Navigable
Map

Navigable
Set

RandomAccess

Vector

Stack

TreeSet

HashSet

LinkedHashSet

EnumSet

TreeMap

HashMap

LinkedHashMap

IdentityH
ashMap

WeakH
ashMap

Enum
Map

Principal collection
class

Base class

Base interfaces

Allow
Ordered? Sorted?
duplicate
elements?
Yes
Yes
No
Yes
Yes
No

Threadsafe?

ArrayList<E>
LinkedList<E>

AbstractList<E>
List<E>
AbstractSequentialList<E> List<E>;

Vector<E>
HashSet<E>
LinkedHashSet<E>
TreeSet<E>

AbstractList<E>
AbstractSet<E>
HashSet<E>
AbstractSet<E>

Yes
No
No
No

Yes
No
Yes
Yes

No
No
No
Yes

Yes
No
No
No

AbstractMap<K, V>
HashMap<K, V>

SortedSet<E>
Map<K, V>
Map<K, V>

No
No

No
Yes

No
No

No
No

Dictionary<K, V>
AbstractMap<K, V>

Map<K, V>
Map<K, V>;

No
No

No
Yes

No
Yes

Yes
No

Deque<E>
List<E>
Set<E>
Set<E>
Set<E>;

No
No

NavigableSet<E>;

HashMap<K, V>
LinkedHashMap<K,
V>
Hashtable<K, V>
TreeMap<K, V>

NavigableMap<K,
V>;
SortedMap<K, V>
o
o
o
o
o

All lists allow duplicate elements which are ordered by index.


All sets and maps do not allow duplicate elements.
All list elements are not sorted.
Generally, sets and maps do not sort its elements, except TreeSet and TreeMap which sort elements by natural
order or by a comparator.
Generally, elements within sets and maps are not ordered, except for:

LinkedHashSet and LinkedHashMap have elements ordered by insertion order.


TreeSet and TreeMap have elements ordered by natural order or by a comparator.
There are only two collections are thread-safe: Vector and Hastable. The rest is not thread-safe.

Ordering : it means there is a proper way you can predict the traversal of the content of a data holder like fifo or lifo
Sorting : it is a type of ordering which adheres some special ordering algorithm apart from the insertion order. like ascending or descending

Description

Allow duplicates
Allow nulls
Insertion order

Sub-interfaces

Common
implementations

Collection
A group of objects
Parent of the
collection hierarchy
Implementation
dependent
Implementation
dependent
Implementation
dependent

List
A sequence of
objects
Position aware
(zero-based)
Yes

Queue
A group of objects
waiting to be
processed

Deque
A group of objects
waiting to be
processed

Set
An abstraction of
the mathematical
set

Yes

Yes

No

Yes

No

No

At most one

Append at end or by
specific position
(index)

First-in, first out


(FIFO)

First-in, first-out
(FIFO) like a queue
or last-in, first-out
(LIFO) like a stack

Implementation
dependent

Set
SortedSet
NavigableSet
List
Queue
Deque
ArrayList
LinkedList

Deque

PriorityQueue
LinkedList
ArrayDeque

SortedSet
NavigableSet

ArrayDeque
LinkedList

HashSet
LinkedHashSet
TreeSet

Map
A key-value pairing
of objects
Do not inherit
Collection interface
Keys cannot
duplicate
At most one null key
Values can be null
Implementation
dependent

SortedMap
NavigableMap

HashMap
LinkedHashMap
TreeMap

Collections Class: This class consists exclusively of static fields/methods that operate on or return collections. The methods of this class all
throw a NullPointerException if the collections or class objects provided to them are null. The "destructive" algorithms contained in this
class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException.

static <T> Boolean

addAll(Collection<? super T> c, T... elements)

Adds all of the specified elements to the specified collection.


static <T> Queue<T>
static <T> int

asLifoQueue(Deque<T> deque)
Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
binarySearch(List<? extends Comparable<? super T>> list, T key)

Searches the specified list for the specified object using the binary search algorithm.
static <T> int

binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

Searches the specified list for the specified object using the binary search algorithm.
static <E> Collection<E>

checkedCollection(Collection<E> c, Class<E> type)

Returns a dynamically typesafe view of the specified collection.


static <E> List<E>

checkedList(List<E> list, Class<E> type)

Returns a dynamically typesafe view of the specified list.


static <K,V> Map<K,V>

checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)

Returns a dynamically typesafe view of the specified map.


static <E> Set<E>

checkedSet(Set<E> s, Class<E> type)

Returns a dynamically typesafe view of the specified set.


static <K,V> SortedMap<K,V>

checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)

Returns a dynamically typesafe view of the specified sorted map.


static <E> SortedSet<E>

checkedSortedSet(SortedSet<E> s, Class<E> type)

Returns a dynamically typesafe view of the specified sorted set.


static <T> void

copy(List<? super T> dest, List<? extends T> src)

Copies all of the elements from one list into another.


static Boolean
static <T> Enumeration<T>

disjoint(Collection<?> c1, Collection<?> c2)


Returns true if the two specified collections have no elements in common.
emptyEnumeration()

Returns an enumeration that has no elements.


static <T> Iterator<T>

emptyIterator()

Returns an iterator that has no elements.


static <T> List<T>

emptyList()

Returns the empty list (immutable).


static <T> ListIterator<T>

emptyListIterator()

Returns a list iterator that has no elements.


static <K,V> Map<K,V>

emptyMap()

Returns the empty map (immutable).


static <T> Set<T>

emptySet()

Returns the empty set (immutable).


static <T> Enumeration<T>

enumeration(Collection<T> c)

Returns an enumeration over the specified collection.


static <T> void

fill(List<? super T> list, T obj)

Replaces all of the elements of the specified list with the specified element.
static int

frequency(Collection<?> c, Object o)

Returns the number of elements in the specified collection equal to the specified object.
static int

indexOfSubList(List<?> source, List<?> target)

Returns the starting position of the first occurrence of the specified target list within the specified
source list, or -1 if there is no such occurrence.
static int

lastIndexOfSubList(List<?> source, List<?> target)

Returns the starting position of the last occurrence of the specified target list within the specified
source list, or -1 if there is no such occurrence.
static <T> ArrayList<T>

list(Enumeration<T> e)

Returns an array list containing the elements returned by the specified enumeration in the order
they are returned by the enumeration.
static <T extends Object &
Comparable<? super T>>
T

max(Collection<? extends T> coll)

static <T> T

max(Collection<? extends T> coll, Comparator<? super T> comp)

Returns the maximum element of the given collection, according to the natural ordering of its
elements.
Returns the maximum element of the given collection, according to the order induced by the
specified comparator.

static <T extends Object &


Comparable<? super T>>
T

min(Collection<? extends T> coll)

static <T> T

min(Collection<? extends T> coll, Comparator<? super T> comp)

Returns the minimum element of the given collection, according to the natural ordering of its
elements.
Returns the minimum element of the given collection, according to the order induced by the
specified comparator.

static <T> List<T>

nCopies(int n, T o)

Returns an immutable list consisting of n copies of the specified object.


static <E> Set<E>

newSetFromMap(Map<E,Boolean> map)

Returns a set backed by the specified map.


static <T> Boolean

replaceAll(List<T> list, T oldVal, T newVal)

Replaces all occurrences of one specified value in a list with another.


static void

reverse(List<?> list)

Reverses the order of the elements in the specified list.

static <T> Comparator<T>

reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that
implement the Comparable interface.
static <T> Comparator<T>

reverseOrder(Comparator<T> cmp)

Returns a comparator that imposes the reverse ordering of the specified comparator.
static void

rotate(List<?> list, int distance)

Rotates the elements in the specified list by the specified distance.


static void

shuffle(List<?> list)

Randomly permutes the specified list using a default source of randomness.


static void

shuffle(List<?> list, Random rnd)

Randomly permute the specified list using the specified source of randomness.
static <T> Set<T>

singleton(T o)

Returns an immutable set containing only the specified object.


static <T> List<T>

singletonList(T o)

Returns an immutable list containing only the specified object.


static <K,V> Map<K,V>

singletonMap(K key, V value)

Returns an immutable map, mapping only the specified key to the specified value.
static <T extends
Comparable<? super T>>
void
static <T> void

sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements.
sort(List<T> list, Comparator<? super T> c)

Sorts the specified list according to the order induced by the specified comparator.
static void

swap(List<?> list, int i, int j)

Swaps the elements at the specified positions in the specified list.


static <T> Collection<T>

synchronizedCollection(Collection<T> c)

Returns a synchronized (thread-safe) collection backed by the specified collection.


static <T> List<T>

synchronizedList(List<T> list)

Returns a synchronized (thread-safe) list backed by the specified list.


static <K,V> Map<K,V>

synchronizedMap(Map<K,V> m)

Returns a synchronized (thread-safe) map backed by the specified map.


static <T> Set<T>

synchronizedSet(Set<T> s)

Returns a synchronized (thread-safe) set backed by the specified set.


static <K,V> SortedMap<K,V>

synchronizedSortedMap(SortedMap<K,V> m)

Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
static <T> SortedSet<T>

synchronizedSortedSet(SortedSet<T> s)

Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
static <T> Collection<T>

unmodifiableCollection(Collection<? extends T> c)

Returns an unmodifiable view of the specified collection.


static <T> List<T>

unmodifiableList(List<? extends T> list)

Returns an unmodifiable view of the specified list.


static <K,V> Map<K,V>

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

Returns an unmodifiable view of the specified map.


static <T> Set<T>

unmodifiableSet(Set<? extends T> s)

Returns an unmodifiable view of the specified set.


static <K,V> SortedMap<K,V>

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

Returns an unmodifiable view of the specified sorted map.


static <T> SortedSet<T>

unmodifiableSortedSet(SortedSet<T> s)

Returns an unmodifiable view of the specified sorted set.


Collection Interface: A Collection represents a group of objects known as its elements. The root interface in the collection hierarchy. The Java
platform doesnt provide any direct implementations of this interface, but rather through its subinterface Set, List
Boolean
Boolean
Void
Boolean
Boolean
Boolean
Int
Boolean
Iterator<E>
Boolean
Boolean
boolean
int
Object[]
<T> T[]

add(E e) Ensures that this collection contains the specified element (optional operation).
addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to this
clear() Removes all of the elements from this collection (optional operation).
contains(Object o) Returns true if this collection contains the specified element.
containsAll(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.
equals(Object o) Compares the specified object with this collection for equality.
hashCode() Returns the hash code value for this collection.
isEmpty() Returns true if this collection contains no elements.
iterator() Returns an iterator over the elements in this collection.
remove(Object o) Removes a single instance of the specified element from this collection, if it is present
removeAll(Collection<?> c) Removes all of this collection's elements that are also contained in the specified collection
retainAll(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection
size() Returns the number of elements in this collection.
toArray() Returns an array containing all of the elements in this collection.
toArray(T[] a) Returns an array containing all of the elements in this collection; the runtime type of the returned array is

that of the specified array.

ArrayList : Java ArrayList represents an automatic re-sizable array and used in place of array. ArrayList supports dynamic arrays that can grow as
needed.
ArrayList gives fast iteration and fast random access. But insertion and deletion is slow, because arraylist needs to adjust the index
ArrayList implementation has excellent performance for indexed access and update of elements
When an arraylist capacity is used, the new array is built 50% bigger than the old one. Default size of an arraylist is 10 element.
Not synchronised, allows duplicates, allows null values, maintaines insertion order.
ArrayList are fail-fast it means if ArrayList 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: While an ArrayList uses an array internally to store the data, a LinkedList uses nodes to hold the elements. These nodes then point
to each other, thus leading to the name "Linked" List.
Performance on insertion and deletion is better, as they are implemented as doubly linked list.
Permits null values, iterators returned by linkedlist are fail-fast. But accessing elements is slower than arraylist.
Vector: Vector is almost identical to ArrayList, and the difference is that Vector is synchronized. Because of this, it has an overhead than
ArrayList. Normally, most Java programmers use ArrayList instead of Vector because they can synchronize explicitly by themselves. Enumerators
returned by Vectors are not Fail-fast.
Set: Allows utmost one null value and no duplicates.
HashSet : Implemented using Hashtable. Slower than arraylist if you want to iterate. Does not allow duplicates, does not guarantee order of
elements.
LinkedHashSet: is between HashSet and TreeSet. It is implemented as a hash table with a linked list running through it, so it provides the order
of insertion
TreeSet: Implemented using tree structure(red-black tree algorithm). Doesnt allow null.
EnumSet: A specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type
that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is
extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe

alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their
argument is also an enum set.
HashSet and TreeSet:
First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of
element is not required.
HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo()
method to compare keys and compareTo() will throw java.lang.NullPointerException
HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.
HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same
purpose.
HashSet doesn't guaranteed any order while TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in
Java
Map: allows utmost one null key, but there can be any number of null values.
HashMap: is a Hash table based implementation. permits null values and the null key. The HashMap class is roughly equivalent to Hashtable,

except that it is unsynchronized and permits nulls. Doesnt guarantee order.


Whenever we try to insert duplicate keys, the last value entered will be set as the value against that key. Eg.
Map<String,String> map = new HashMap<String,String>();
map.put("a", null);
map.put("b", null);
map.put(null, "san");
map.put(null, "aadu");
map.put("a", "bbb");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() +" ** "+ entry.getValue());
}
The output for the above code is:
null ** aadu // first value san is overridden

b ** null
a ** bbb //first value null is overridden
WeakHashMap: Both null values and the null key are supported. Elements in a weak hashmap can be reclaimed by the garbage collector if there

are no other strong references to the object, this makes them useful for caches/lookup storage. Weak reference are not restricted to these hash
tables, you can use WeakReference for single objects. They are useful to save resource, you can keep a reference to something but allow it to be
collected when nothing else references it. Accepts null keys/values.
LinkedHashMap: LinkedHashMap is a combination of Hash table and linked list implementation of the Map interface, with predictable iteration

order. Takes null keys and values.


Map<String,String> map = new LinkedHashMap<String,String>();
map.put("a", "nulllll");
map.put(null, null);
map.put(null, "san");
map.put("b", "aadu");
map.put("a", null);
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() +" ** "+ entry.getValue());
}
The output is:
a ** null
null ** san
b ** aadu
TreeMap: TreeMap is a Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or

by a Comparator provided at map creation time. No null keys is accepted. But null values are allowed.
EnumMap: A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type
that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is
extremely compact and efficient. Enum maps are maintained in the natural order of their keys
Hashtable: java.util.Hashtable extends Dictionary and implements Map. Objects with non-null value can be used as a key or value. When the
Value/Key is Null then NPE is thrown. Key of the Hashtable must implement hashcode() and equals() methods. If keys are duplicates, then final
value is considered. Eg:

Map<String,String> map = new Hashtable<String,String>();


map.put("a", "null");
map.put("b", "null");
map.put("b", "san");
map.put("b", "aadu");
map.put("a", "bbb");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() +" ** "+ entry.getValue());
}
The output is:
b ** aadu
a ** bbb

Generally a Hashtable in java is created using the empty constructor Hashtable(). Which is a poor decision and an often repeated mistake.
Hashtable has two other constructors
Hashtable(int initialCapacity) and

Hashtable(int initialCapacity, float loadFactor)

Initial capacity is number of buckets created at the time of Hashtable instantiation. Bucket is a logical space of storage for Hashtable.
How is HashMap internally implemented?
Key/Value pair is stored in HashMap. Pair is an entry to hashMap. Entries are stored in an array. So we have an array of entries.
Each Entry has a key. We calculate hash(key.hashcode()), which determines the index in array. hash method shortens the hashcode value to a
valid int index.

this is the main array

[Entry] Entry Entry


[Entry]
[Entry] Entry
[Entry]
[null ]
[null ]

here is the linked-list

The value at any index in array is called bucket, which holds the Entry.
If for two Entries index comes out to be same, while storing. This is possible if two keys have same hashCode value. Then those two entries are
stored in same bucket. Bucket is a linkedlist at any index in array, and bucket holds the Entries. So we can have multiple entries in same bucket.
When get(Key) operation is called. We do following 1. Calculate the hash(key.hashcode()), so that we know the index of the bucket in array.
2. If bucket holds more than one Key, use equals(on key) to return the exact match.
Iterable: Implementing this interface allows an object to be the target of the "foreach" statement.
Iterator<T> iterator()Returns an iterator over a set of elements of type T.

Iterator : An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from
enumerations in two ways:

Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.

boolean
E
void

hasNext() Returns true if the iteration has more elements.


next() Returns the next element in the iteration.
remove()

Removes from the underlying collection the last element returned by this iterator (optional operation).
Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the
nextElement method return successive elements of the series. Prefer Iterator to this method as that provides additional methods remove
operation, and has shorter method names.
boolean

hasMoreElements()

Tests if this enumeration contains more elements.


E

nextElement()

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Queue: A collection designed for holding elements prior to processing. Besides basic collection operations, queue provides the following
operations:
All Superinterfaces: Collection<E>, Iterable<E>
All Known Subinterfaces: BlockingDeque<E>, BlockingQueue<E>, Deque<E>, TransferQueue<E>
All Known Implementing Classes: AbstractQueue, ArrayBlockingQueue, ArrayDeque, ConcurrentLinkedDeque, ConcurrentLinkedQueue,
DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue,
SynchronousQueue
boolean

E
boolean

add(E e)

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning
true upon success and throwing an IllegalStateException if no space is currently available.
element() Retrieves, but does not remove, the head of this queue.
offer(E e)

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove() Retrieves and removes the head of this queue.
PriorityQueue: The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue
construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural
ordering also does not permit insertion of non-comparable objects
E
E
E

Deque: A linear collection that supports element insertion and removal at both ends. A linear collection that supports element insertion and
removal at both ends. The name deque is short for "double ended queue"
Queue Method
add(e)
offer(e)
remove()
poll()
element()
peek()
Sorting:

Equivalent Deque Method


addLast(e)
offerLast(e)
removeFirst()
pollFirst()
getFirst()
peekFirst()

//sort primitives array like int array


int[] intArr = {5,9,1,10};
Arrays.sort(intArr);
System.out.println(Arrays.toString(intArr));
//sorting String array
String[] strArr = {"A", "C", "B", "Z", "E"};
Arrays.sort(strArr);
System.out.println(Arrays.toString(strArr));
//sorting list of objects of Wrapper classes
List<String> strList = new ArrayList<String>();
strList.add("A");
strList.add("C");
strList.add("B");
strList.add("Z");
strList.add("E");
Collections.sort(strList);
for(String str: strList) System.out.print(" "+str);

when you try to call Arrays.sort(empArray) u will get ClassCastException


Comparing custom objects using Comparable interface and Comparator interface
Comparable interface: Comparable interface is used to order the objects of user-defined class. This interface is found in java.lang package and
contains only one method named compareTo(Object).It provide only single sorting sequence i.e. you can sort the elements on based on single
datamember only.For instance it may be either rollno,name,age or anything else.
public int compareTo(Object obj): is used to compare the current object with the specified object.
We can sort the elements of: String objects, Wrapper class objects, User-defined class objects
String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be
Comparable.
class Employee implements Comparable<Employee> {
String name;
int no;

public Employee(String name, int no) {


super();
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int compareTo(Employee e) {
//return (this.name).compareTo(e.getName());
//return (e.getNo())-(this.no) ; -- desc order
//return (e.getName()).compareTo(this.name); -- desc order
return (this.no) - (e.getNo());
}
}
Sample.java
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
empList.add(new
empList.add(new
empList.add(new
empList.add(new

Employee("sandu", 32));
Employee("vijay", 35));
Employee("adithya", 2));
Employee("aadarsh", 7));

Collections.sort(empList);
for (Employee emp : empList) {
System.out.println(emp.getName() + "******" + emp.getNo());
}
}

Comparator interface: is used to order the objects of user-defined class. This interface is found in java.util package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element). It provides multiple sorting sequence i.e. you can sort the elements based on any
data member. For instance it may be on rollno, name, age or anything else. int compare(obj1, obj2)
public class Sample {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
empList.add(new
empList.add(new
empList.add(new
empList.add(new
empList.add(new
empList.add(new

Employee("sandu", 32));
Employee("vijay", 35));
Employee("adithya", 2));
Employee("aadarsh", 7));
Employee("deepu",14));
Employee("deepu",2));

Collections.sort(empList, new Employee());


for (Employee emp : empList) {
System.out.println(emp.getName() + "******" + emp.getNo());
}
}
}
class Employee implements Comparator<Employee> {
String name;
int no;
public Employee() {
}
public Employee(String name, int no) {
super();
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public int getNo() {


return no;
}
public void setNo(int no) {
this.no = no;
}
public int compare(Employee e1, Employee e2) {
int flag = e1.getNo() - e2.getNo(); //first compare no.
if(flag==0) flag = e1.getName().compareTo(e2.getName()); //then compare name
return flag;
}
}

Output:
adithya******2
deepu******2
aadarsh******7
deepu******14
sandu******32
vijay******35
==================
Example : 2
public class Sample {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
empList.add(new
empList.add(new
empList.add(new
empList.add(new
empList.add(new
empList.add(new

Employee("sandu", 32));
Employee("vijay", 35));
Employee("adithya", 2));
Employee("aadarsh", 7));
Employee("deepu",14));
Employee("deepu",2));

Collections.sort(empList, Employee.NumberComparator);
//Collections.sort(empList, Employee.NameComparator);
for (Employee emp : empList) {
System.out.println(emp.getName() + "******" + emp.getNo());

}
}
}
class Employee implements Comparator<Employee> {
String name;
int no;
public Employee() {
}
public Employee(String name, int no) {
super();
this.name = name;
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int compare(Employee e1, Employee e2) {
int flag = e1.getNo() - e2.getNo(); //first compare no.
if(flag==0) flag = e1.getName().compareTo(e2.getName()); //then compare name
return flag;
}
// Comparator to sort employees list or array in order of Name
public static Comparator<Employee> NameComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
};

// Comparator to sort employees list or array in order of No


public static Comparator<Employee> NumberComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getNo() - e2.getNo();
}
};
}
Output:
adithya******2
deepu******2
aadarsh******7
deepu******14
sandu******32
vijay******35

Observer A class can implement the Observer interface when it wants to be informed of changes in observable objects.
update(Observable o, Object arg)
void

This method is called whenever the observed object is changed.


Observable It can be subclassed to represent an object that the application wants to have observed.
public void addObserver(Observer obs)

Adds an observer to the internal list of observers.


public void deleteObserver(Observer obs)

Deletes an observer from the internal list of observers.


public void deleteObservers()

Deletes all observers from the internal list of observers.


public int countObservers()

Returns the number of observers in the internal list of observers.

Thread Basics :
Process: A process is a self contained execution environment and it can be seen as a program or application. However a program itself contains
multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.
Thread: Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process
resources. Every java application has at least one thread main thread. Although there are so many other threads running in background like
memory management, system management, signal processing etc. But from application point of view main is the first thread and we can
create multiple threads from it.
Daemon Vs. User Thread: When we create a Thread in java program, its known as user thread. A daemon thread runs in background and
doesnt prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created
from daemon thread is also a daemon thread.
Benefits of thread:
Threads are lightweight compared to processes, it takes less time and resource to create a thread.
Threads share their parent process data and code
Context switching between threads is usually less expensive than between processes.
Thread intercommunication is relatively easy than process communication.
Java provides two ways to create a thread programmatically.

Java Thread By Implementing Runnable Interface

A Thread can be created by extending Thread class also. But Java allows only one class to extend, it wont allow multiple inheritance. So it
is always better to create a thread by implementing Runnable interface. Java allows you to impliment multiple interfaces at a time.
By implementing Runnable interface, you need to provide implementation for run() method.
To run this implementation class, create a Thread object, pass Runnable implementation class object to its constructor. Call start()
method on thread class to start executing run() method.
Implementing Runnable interface does not create a Thread object, it only defines an entry point for threads in your object. It allows you
to pass the object to the Thread(Runnable implementation) constructor.

public class Worker implements Runnable


{

public static void main (String[] args)


{
System.out.println("This is currently running on the main thread, " +
"the id is: " + Thread.currentThread().getId());
Worker worker = new Worker();
Thread thread = new Thread(worker);
thread.start();
}
@Override
public void run()
{
System.out.println("This is currently running on a separate thread, " +
"the id is: " + Thread.currentThread().getId());
}
}
2.Extending the java.lang.Thread class - extend java.lang.Thread class to create our own thread class and override run() method. Then we can

create its object and call start() method to execute our custom thread class run method.
public class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
System.out.println("MyThread - START "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
//Get database connection, delete unused data from DB
doDBProcessing();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("MyThread - END "+Thread.currentThread().getName());
}
private void doDBProcessing() throws InterruptedException {

Thread.sleep(5000);
}

Runnable Vs. Thread


If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it
as Thread. If your class only goal is to run as Thread, you can extend Thread class.
Implementing Runnable is preferred because java supports implementing multiple interfaces. If you extend Thread class, you cant extend any
other classes.
Thread states /Life cycle of Thread
New : When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and its a state
internal to Java programming
Runnable: When we call start() function on Thread object, its state is changed to Runnable and the control is given to Thread scheduler to finish
its execution. Whether to run this thread instantly or keep it in runnable thread pool before running it depends on the OS implementation of
thread scheduler.
Running: When thread is executing, its state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and
change its state to Running and CPU starts executing this thread.
Blocked/Waiting: A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available, for
example producer consumer problem or waiter notifier implementation or IO resources, then its state is changed to Waiting. Once the thread
wait state is over, its state is changed to Runnable and its moved back to runnable thread pool.
Dead: Once the thread finished executing, its state is changed to Dead and its considered to be not alive.
A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread
and passing itself in as the target.
Thread class methods

waits for this thread to die. You can wait for a thread to finish by calling its join() method.

ject to pause temporarily and gives control to other thread to execute.


Object class methods on thread:Inherited from Object class. This method wakes up a single thread that is waiting on this object's monitor to acquire lock.
(): Inherited from Object class. This method wakes up all threads that are waiting on this object's monitor to acquire lock.
Inherited from Object class. This method makes current thread to wait until another thread invokes the notify() or the notifyAll() for
this object.
Synchronization:
Synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock, at this
point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates
memory inconsistency errors.
You can have both static synchronized method and non static synchronized method and synchronized blocks in Java but we can not have
synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of synchronized
variable in Java, you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and
dont cache it locally. Block synchronization in Java is preferred over method synchronization in Java because by using block synchronization, you
only need to lock the critical section of code instead of whole method. Since synchronization in Java comes with cost of performance, we need
to synchronize only part of code which absolutely needs to be synchronized.
What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current
object (this).
Concurrency(java.util.concurrent)
java.util.concurrent:
Java 5 added a new Java package to the Java platform, the java.util.concurrent package. This package contains a set of classes that makes
it easier to develop concurrent (multithreaded) applications in Java.
Types in the Java Concurrency Utilities are organized into small frameworks; namely, Executor framework, synchronizer, concurrent collections,
locks, atomic variables, and Fork/Join
ConcurrentHashMap<K,V>

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.

ConcurrentLinkedDeque<E>
ConcurrentLinkedQueue<E>
ConcurrentSkipListMap<K,V>
ConcurrentSkipListSet<E>
CopyOnWriteArrayList<E>
CopyOnWriteArraySet<E>
ConcurrentMap<K,V>

An unbounded concurrent deque based on linked nodes.


An unbounded thread-safe queue based on linked nodes.
A scalable concurrent ConcurrentNavigableMap implementation.
A scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.
A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by
making a fresh copy of the underlying array.
A Set that uses an internal CopyOnWriteArrayList for all of its operations.
A Map providing additional atomic putIfAbsent, remove, and replace methods.

Atomic Operations: Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are
necessity in multi-threaded environment to avoid data inconsistency.
Lock Interface (Java Concurrency API) - Lock interface provide more extensive locking operations than can be obtained using synchronized
methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated
Condition objects.
The advantages of a lock are

its possible to make them fair


its possible to make a thread responsive to interruption while waiting on a Lock object.
its possible to try to acquire the lock, but return immediately or after a timeout if the lock cant be acquired
its possible to acquire and release locks in different scopes, and in different orders

Lock striping and ConcurrentHashMap


Synchronizing on the whole map fails to take advantage of a possible optimisation: because hash maps store their data in a series of separate
buckets, it is in principle possible to lock only the portion of the map that is being accessed. This optimisation is generally called lock striping.
Java 5 brings a hash map optimised in this way in the form of ConcurrentHashMap. A combination of lock striping plus judicious use of volatile
variables gives the class two highly concurrent properties:

Writing to a ConcurrentHashMap locks only a portion of the map;


Reads can generally occur without locking.

Explicit Locking:
Synchronized keyword allows exclusive locking at the level of a block or method. The standard form of locking provided by the synchronized
keyword has limitations:
1.
2.
3.
4.

Once a thread decides to enter a synchronized section, it commits to potentially waiting forever for the lock to become available
Only one thread can hold the lock at once:
Locking with synchronized happens purely at the block level:
From our Java program, we can't get any "metadata" about the lock: that is performance information such as how many threads are
currently waiting on the lock, on average how long it takes to acquire the lock etc

Explicit locks are useful in cases where you need to overcome some of the shortcomings of built-in synchronization. In particular, they
have the following features:

A thread can attempt to acquire a lock interruptibly;


A thread can give a timeout value for attempting to acquire the lock;
Read/write locks are supported that is, locks that allow multiple concurrent readers if the lock is not locked for writing;
The traditional wait/notify metaphor is extended to allow conditions (see below);
Support for fairness (if more than one thread is waiting for a lock, they acquire in first-in-first-out order when it becomes available);
The ability to lock beyond the scope of a block: for example, one method can pass a lock object to another thread;
Locks can be queried to find out, for example, if they currently have any threads waiting to acquire them.

Interview Questions:
List list = Collections.synchronizedList(new LinkedList(...));
List list = Collections.synchronizedList(new ArrayList(...));

How to make a List (ArrayList,Vector,LinkedList) read only?


A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add
operation on the new list; UnSupportedOperationException is thrown.
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of
Employee class. What are the steps?
Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
Now call Collections.sort() method and pass list as an argument.
How about when Employee class is a jar file and you do not have access to its source code?
Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
Call Collections.sort() on the list and pass Comparator as an argument.
How do we check if the arraylist contains duplicates- dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll),
then see if the Set has the same size as the ArrayList.
List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates */
}

Compare two list to check if list 1 contains any elements of list 2

List arrayList = new ArrayList();


List arrayList1 = new ArrayList();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(3);
arrayList1.add(4);
arrayList1.add(5);
arrayList1.add(3);
Iterator it = arrayList.iterator();
while(it.hasNext())
{
Object i=it.next();
if(arrayList1.contains(i)){
System.out.println("contains" + i);
}
}
Output:
contains3
contains4
contains3

How to avoid ConcurrentModificationException in multithreaded environment:


1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large
then it will affect the performance a lot.
2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits
of multithreading.
3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.
What is difference between Enumeration and Iterator interface?

java.util.Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is
much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying
collection that is not possible with Enumeration. Iterator method names have been improved to make its functionality clear.
What is different between Iterator and ListIterator?

We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.
Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting
index position for previous and next elements.

SimpleDateFormat : used for formatting and parsing dates.


Date d = new Date();
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(d + **************** + s.format(d));

Output: Thu Jul 17 13:35:35 EDT 2014**************07-17-2014


Converting a String to Date :
String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss").format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);

Convert util date to sql date?


java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

utilDate:Fri Feb 02 12:55:46 PST 2007

sqlDate:2007-02-02

Deque
Queue

BlockingQueue

AbstractQueue

BlockingDeque

TransferQueue

ArrayBlock
ingQueue

Delay
Queue

LinkedBlock
ingQueue

PriorityBlock
ingDeque

Priority
Queue

LinkedBlock
ingDeque

ArrayDeque

Potrebbero piacerti anche