Sunday, November 30, 2014
Java Collections
Hashmap:
Building Blocks:
Internal Data Structure: Array - Entry[] table=new Entry[capacity];
static class Entry<K,V>{final K key;
V value;
Entry<K,V> next;
final int hash;
}
Hash Collisions: If multiple key have same hash it results in to hash collision. To handle this a linkedlist is formed using next reference. While retrieval, this linkedlist has to be iterated and check for equality of the key object to return the corresponding value.
Capacity:
(Default value 16)
Capacity is the length of the array or number of buckets in the hashmap. A bucket corresponds to an index of the array.
This can be initialized with different value.
Map<String,String> map = new HashMap<String,String>(capacity);
Load Factor: (Default value 0.75)
Load factor is the measure how full is the hashtable allowed to get before its capacity is automatically increased.
Threshold: This is the next size of elemnts in hashmap at which hashmap will resize.
Threshold= capacity * loadfactor.
Capacity will be increased by twice once element size reaches to threshold.
if( size >= threashold){ //if size after last add call >= threashold then resize table
resize(2*table.length);
}
resize(2*table.length);
}
API Snippet
Related Interview Questions:
1. Equals and Hashcode
2. Concurrency
3. Immutability
4. Clone (shallow copy vs Deep Copy)
5. Why capacity size is poer of two?
6. Read/Write Performance
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
}
1. Equals and Hashcode
2. Concurrency
3. Immutability
4. Clone (shallow copy vs Deep Copy)
5. Why capacity size is poer of two?
6. Read/Write Performance
LinkedHashMap
Linkedhashmap extends Hashmap to maintain insertion order of elements. It also maintain the access order and can be used to implement LRU based cache.
It maintains doubly linkedlist running through all of its entries.
Entry:
static class Entry<K,V> extends HashMap.Entry<K,V>{
Entry<K,V> before, after;
Entry(int hash, K key, V value, HashMap.Entry<K,V) next){
super(hash,key,value,next);
}
}
Header:
Entry<K,V> header;
//construction or initialization
header = new Entry<>(-1, null, null, null);
header.before = header.after = header;
//construction or initialization
header = new Entry<>(-1, null, null, null);
header.before = header.after = header;
AccessOrder :
boolean accessOrder;
public LinkedHashMap(){
super();
accessOrder = false;
}
Add Entry:
void addEntry(int hash, K key, V value, int bucketIndex) {
createEntry(hash, key, value, bucketIndex);
// Remove eldest entry if instructed, else grow capacity if appropriate
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
} else {
if (size >= threshold)
resize(2 * table.length);
}
}
void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);
size++;
}
public LinkedHashMap(){
super();
accessOrder = false;
}
Add Entry:
void addEntry(int hash, K key, V value, int bucketIndex) {
createEntry(hash, key, value, bucketIndex);
// Remove eldest entry if instructed, else grow capacity if appropriate
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
} else {
if (size >= threshold)
resize(2 * table.length);
}
}
void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header);
size++;
}
private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
}
Concurrent Hashmap
Data Structure and Algorithm
Graphs
Representation
1. Using Edge List
2. Using Adjacent Matrix
3. Using Adjacent List
Thursday, November 27, 2014
JDK version features
JDK 1.5 Features
1)
Generics
2)
Enhanced For Loop
3)
Autoboxing/Unboxing
4)
TypeSafe enums
5)
Static import
6)
Declarative
programming(Metadata/Annotations)
7)
Concurrent Package
8)
Var args
9)
Scanner
JDK 1.5 Concurrency
Limitations
of JDK 1.4 Synchronization
1.
No
way to back off or wait time out or cancellation once lock is held.
2.
Lock
semantics can not be changed- Re-entrancy, read vs write protection or fairness
3.
No
access control for synchronization
4.
Lock
and unlock cannot be done outside of a method.
Concurrency Features
-
Task scheduling
framework: Executor Framewrok
-
Concurrent
Collections: Queue, Blocking Queue, Concurrent Hahshmap, List and Queue
-
Atomic
Variables: AtomicInteger etc.
-
Locks:
-
Nanonsecond
granularity timing
-
Utility classes
for synchronization
o
Semaphore
o
CyclicBarrier
o
CountDownLatch
o
Exchanger
JDK 7 – New Features
1.
switch
block with string
for (String arg: args) {
switch (arg) {
case "-c": create = true;
break;
case "-v": verbose =
true; break;
case "-d": debug = true;
break;
default:
System.out.println("invalid
option");
System.exit(1);
}
}
2.
Binary
Literals with prefix 0b e.g int number1 =
0b01010000101000101101000010100010;
3.
_
for numerical Literlas
short aShort =
(short)0b0111_0101_0000_0101;
4.
Catching
Multiple Exception Types
try {
......
}
catch(ClassNotFoundException|SQLException ex) {
ex.printStackTrace();
}
5.
The
try-with-resource Statement (Auto-close resources)
public class FileCopyJDK7
{
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new
FileReader("in.txt"));
BufferedWriter out = new
BufferedWriter(new FileWriter("out.txt"))) {
int charRead;
while ((charRead = in.read()) != -1) {
System.out.printf("%c ",
(char)charRead);
out.write(charRead);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
6.
Type
Interference for Generic Instance Creation . e.g. List<String> lst1 = new ArrayList<String>();
7.
Fork and Join
JDK 8– New Features
1)
Lambda expressions
btn.setOnAction(new
EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello
World!");
}
});
With lambda in java 8
you just have:
btn.setOnAction(
event -> System.out.println("Hello
World!")
);
2)
Remove the Permanent
Generation
3)
Small VM
4)
Parallel Array Sorting
5)
Bulk Data Operations for
Collections
6)
Define a standard API
for Base64 encoding and decoding
7)
New Date & Time API
8)
Provide stronger
Password-Based-Encryption (PBE) algorithm implementations in the SunJCE
provider
Advanced Java Interview Questions
1. How does Hashmap work internally?(Load factor, capacity,hash chaining/collision, equals and hashcode, immutability of key,concurrency, Hashmap vs Hashtable)
2. Equals and hashcode
3. Hash collision
4. Load factor in hashmap
5. Immutable class-concept and implementation.
6. Cloning-deep copy vs shallow copy
Multithreading
1. Notify vs NotifyAll
2. Wait vs sleep
3. Synchronized method vs block
4. Static vs non static method synchronized
5. Daemon thread
6. Thread life cycle
7. Threadpool- implementation
8. Threadfactory
9. Interthread communication
10. Thread memory model
11. Volatile
JDK 1.5
1. Concurrent collections- Concurrent Hashmap
2. Executor framework
3. CAS-Aromic integer etc
4. Autoboxing
5. Generics.
6. For each loop
7. Var args
8. Subclass return type
http://www.javacodegeeks.com/2014/04/java-interview-questions-and-answers.html
http://javarticles.com/2012/06/concurrenthashmap.html
2. Equals and hashcode
3. Hash collision
4. Load factor in hashmap
5. Immutable class-concept and implementation.
6. Cloning-deep copy vs shallow copy
Multithreading
1. Notify vs NotifyAll
2. Wait vs sleep
3. Synchronized method vs block
4. Static vs non static method synchronized
5. Daemon thread
6. Thread life cycle
7. Threadpool- implementation
8. Threadfactory
9. Interthread communication
10. Thread memory model
11. Volatile
JDK 1.5
1. Concurrent collections- Concurrent Hashmap
2. Executor framework
3. CAS-Aromic integer etc
4. Autoboxing
5. Generics.
6. For each loop
7. Var args
8. Subclass return type
http://www.javacodegeeks.com/2014/04/java-interview-questions-and-answers.html
http://javarticles.com/2012/06/concurrenthashmap.html
Subscribe to:
Posts (Atom)