Interview Concepts - Yash-777/LearnJava GitHub Wiki

Object as a Superclass

The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class.

protected Object clone() throws CloneNotSupportedException
public boolean equals(Object obj)
protected void finalize() throws Throwable
public final Class getClass()
public int hashCode()
public String toString()

public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)

Collection framework

Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. interface Collection<E>extends Iterable

Iterator is a fail-fast in nature. i.e it throws ConcurrentModificationException if a collection is modified while iterating other than it’s own remove() method. Where as Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.

Fail-fast iterators (those returned by HashMap, ArrayList, and other non-thread-safe collections) iterate over the collection’s internal data structure, and they throw ConcurrentModificationException as soon as they detect a concurrent modification.

Fail-safe iterators (returned by thread-safe collections such as ConcurrentHashMap) create a copy of the structure they iterate upon. They guarantee safety from concurrent modifications. Their drawbacks include excessive memory consumption and iteration over possibly out-of-date data in case the collection was modified. java.util.concurrent packages are fail-safe and we can modify the collection while iterating. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework.
In order to synchronize it we are using Collections.synchronizedMap(hashmap) it returns a thread-safe map backed up by the specified HashMap.

UnsupportedOperationException « Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );

ConcurrentHashMap « ConcurrentModificationException

In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap implementation backed by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates. It is intended as a drop-in replacement for Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.

  • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update.
  • Iterators and Enumerations are Fail Safe - reflecting the state at some point since the creation of iterator/enumeration; this allows for simultaneous reads and modifications at the cost of reduced consistency. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.

Comparable and Comparator interfaces to sort collections

java.lang.Comparable: int compareTo(Object o1) « A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

  • Capable of comparing current object with the provided object.
  • By using this we can implement only one sort sequence based on the instances properties. EX: Person.id
  • Some of the Predefined Classes like String, Wrapper classes, Date, Calendar has implemented Comparable interface.

java.util.Comparator: int compare(Object o1, Object o2) « A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

  • Capable of comparing any two Objects of Same Type.
  • By using this we can implement many sort sequence and name each, based on the instances properties. EX: Person.id, Person.name, Person.age
  • We can implement Comparator interface to our Pre-defined classes for Customized sorting.

java.util.Collections is a utility class consists exclusively of static methods that operate on or return collections.

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).

List<Integer> list1 = Arrays.asList(5, 2, 3, 4, 1);
Collections.sort(list1);
System.out.println("Ascending Order: "+ list1 ); // [1, 2, 3, 4, 5]

List<Integer> list2 = Arrays.asList(5, 2, 3, 4, 1);
Collections.sort(list2, (a, b) -> b - a);
System.out.println("Descending Order:"+ list2 ); // [5, 4, 3, 2, 1]

LinkedList and ArrayList

LinkedList is a doubly-linked list: single elements are put into Node objects that have references to previous and next Node. Insertion of a node objects are very fast.

ArrayList is an implementation of the List interface that is based on an array. ArrayList internally handles resizing of this array when the elements are added or removed. You can access its elements in constant time by their index in the array. However, inserting or removing an element infers shifting all consequent elements System.arraycopy() which may be slow if the array is huge and the inserted or removed element is close to the beginning of the list.

  • ArrayList is not synchronized. It uses Iterator interface to traverse the elements.

  • Vector is a legacy class and synchronized. Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

  • Stack class is the child class of Vector. It follows LIFO (Last in first out) mechanism.

     List<String> al = new ArrayList<String>();//creating arraylist
      al.add("Sonoo");//adding object in arraylist
     
     Vector<String> v = new Vector<String>();//creating vector
      v.add("umesh");//method of Collection
      v.addElement("irfan");//method of Vector
     
     Stack st = new Stack();	 
      // push(Object item), pop(), peek(), empty(), search(Object o)
      st.push("java");
⚠️ **GitHub.com Fallback** ⚠️