Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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) 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.
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
Searches the specified list for the specified object using the binary search algorithm.
static <E> Collection<E>
emptyIterator()
emptyList()
emptyListIterator()
emptyMap()
emptySet()
enumeration(Collection<T> c)
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
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
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
static <T> T
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> T
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.
nCopies(int n, T o)
newSetFromMap(Map<E,Boolean> map)
reverse(List<?> list)
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
shuffle(List<?> list)
Randomly permute the specified list using the specified source of randomness.
static <T> Set<T>
singleton(T o)
singletonList(T o)
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
synchronizedCollection(Collection<T> c)
synchronizedList(List<T> list)
synchronizedMap(Map<K,V> m)
synchronizedSet(Set<T> s)
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>
unmodifiableSortedSet(SortedSet<T> s)
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
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,
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
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:
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
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.
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
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()
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:
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));
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());
}
};
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
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.
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.
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);
}
waits for this thread to die. You can wait for a thread to finish by calling its join() method.
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>
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
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:
Interview Questions:
List list = Collections.synchronizedList(new LinkedList(...));
List list = Collections.synchronizedList(new ArrayList(...));
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.
sqlDate:2007-02-02
Deque
Queue
BlockingQueue
AbstractQueue
BlockingDeque
TransferQueue
ArrayBlock
ingQueue
Delay
Queue
LinkedBlock
ingQueue
PriorityBlock
ingDeque
Priority
Queue
LinkedBlock
ingDeque
ArrayDeque