Monday, December 4, 2017

interview questions -collections



_______________________________________________

How HashMap works in Java ?


in Java?

How to sort a collection of custom Objects in Java?

We need to implement Comparable interface to support sorting of custom objects in a collection. Comparable interface has compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide default way to sort custom objects collection.
However, if you want to sort based on different criteria, such as sorting an Employees collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology. For more details read Java Comparable and Comparator.

Q #24)  What is mean by Collections in Java?
Ans: Collection is a framework that is designed to store the objects and manipulate the design to store the objects.
Collections are used to perform the following operations:
  1. Searching
  2. Sorting
  3. Manipulation
  4. Insertion
  5. Deletion
A group of objects is known as collections. All the classes and interfaces for collecting are available in Java utile package.
Q #25) What are all the Classes and Interfaces that are available in the collections?
Ans: Given below are the Classes and Interfaces that are available in Collections:
Interfaces:
  1. Collection
  2. List
  3. Set
  4. Map
  5. Sorted Set
  6. Sorted Map
  7. Queue
Classes:
  1. Lists:
  2. Array List
  3. Vector
  4. Linked List
Sets:
  1. Hash set
  2. Linked Hash Set
  3. Tree Set
Maps:
  1. Hash Map
  2. Hash Table
  3. Tree Map
  4. Linked Hashed Map
Queue:
  • Priority Queue
Q #26) What is meant by Ordered and Sorted in collections?
Ans:
Ordered:
It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.
Sorted:
Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.
Q #27) Explain about the different lists available in the collection.
Ans: Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed.
Types of Lists are:
Array List:
  • Fast iteration and fast Random Access.
  • It is an ordered collection (by index) and not sorted.
  • It implements Random Access Interface.
Example:
public class Fruits{
public static void main (String [ ] args){
ArrayList names=new ArrayList ();
names.add (“apple”);
names.add (“cherry”);
names.add (“kiwi”);
names.add (“banana”);
names.add (“cherry”);
System.out.println (names);
}
}
Output:
[Apple, cherry, kiwi, banana, cherry]
From the output, Array List maintains the insertion order and it accepts the duplicates. But not sorted.
Vector:
It is same as Array List.
  • Vector methods are synchronized.
  • Thread safety.
  • It also implements the Random Access.
  • Thread safety usually causes a performance hit.
Example:
public class Fruit {
public static void main (String [ ] args){
Vector  names = new Vector  ( );
 names.add (“cherry”);
names.add (“apple”);
names.add (“banana”);
names.add (“kiwi”);
names.add (“apple”);
System.out.println (“names”);
}
}
Output:
[cherry,apple,banana,kiwi,apple]
Vector also maintains the insertion order and accepts the duplicates.
Linked List:
  • Elements are doubly linked to one another.
  • Performance is slow than Array list.
  • Good choice for insertion and deletion.
  • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
Example:
public class Fruit {
public static void main (String [ ] args){
Linkedlist  names = new linkedlist  ( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output
[ banana,cherry,apple,kiwi,banana]
Maintains the insertion order and accepts the duplicates.
Q #28) Explain about Set and their types in a collection?
Ans: Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.
Hash Set:
  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.
Example:
public class Fruit {
public static void main (String[ ] args){
HashSet names = new HashSet <=String>( ) ;
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println (names);
}
}
Output:
[banana, cherry, kiwi, apple]
Doesn’t follow any insertion order. Duplicates are not allowed.
Linked Hash set:
  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when the iteration order is required.
Example:
public class Fruit {
public static void main (String[ ] args){
LinkedHashSet names = new LinkedHashSet ( ) ;
 names.add(“banana”);
 names.add(“cherry”);
 names.add(“apple”);
 names.add(“kiwi”);
 names.add(“banana”);
 System.out.println (names);
 }
}
Output:
[banana, cherry, apple, kiwi]
Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.
Tree Set:
  • It is one of the two sorted collections.
  • Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
  • We can construct a tree set with the constructor by using comparable (or) comparator.
Example:
public class Fruits{
public static void main (String[ ]args) {
Treeset names= new TreeSet( ) ;
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in an ascending order. And duplicates are not allowed.
Q #29). Explain about Map and their types.
Ans: Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different.
Hash Map:
  • Unordered and unsorted map.
  • Hashmap is a good choice when we don’t care about the order.
  • It allows one null key and multiple null values.
Example:
Public class Fruit{
Public static void main(String[ ] args){
HashMap names =new HashMap( );
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
System.out.println(names);
}
 }
Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}
Duplicate keys are not allowed in Map.
Doesn’t maintain any insertion order and is unsorted.
Hash Table:
  • Like vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • Doesn’t allow anything that is null.
Example:
public class Fruit{
public static void main(String[ ]args){
Hashtable names =new Hashtable( );
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
 }
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
Duplicate keys are not allowed.
 Linked Hash Map:
  • Maintains insertion order.
  • Slower than Hash map.
  • Can expect a faster iteration.
Example:
public class Fruit{
public static void main(String[ ] args){
LinkedHashMap names =new LinkedHashMap( );
 names.put(“key1”,“cherry”);
 names.put(“key2”,“apple”);
 names.put(“key3”,“banana”);
 names.put(“key4”,“kiwi”);
 names.put(“key2”,“orange”);
 System.out.println(names);
 }
 }
Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
Duplicate keys are not allowed.
TreeMap:
  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.
Example:
public class Fruit{
public static void main(String[ ]args){
TreeMap names =new TreeMap( );
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
System.out.println(names);
}
}
Output:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}
It is sorted in ascending order based on the key. Duplicate keys are not allowed.
Q #30) Explain the Priority Queue.
Ans: Queue Interface
Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. Purpose of a queue is “Priority-in, Priority-out”.
Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.

Q #21) Difference between HashMap and HashTable.
Ans: Difference between HashMap and HashTable can be seen below:
HashMapHashTable
Methods are not synchronizedKey methods are synchronized
Not thread safetyThread safety
Iterator is used to iterate the valuesEnumerator is used to iterate the values
Allows one null key and multiple null valuesDoesn’t allow anything that is null
Performance is high than HashTablePerformance is slow


Q #22) Difference between HashSet and TreeSet.
Ans: Difference between HashSet and TreeSet can be seen below:
HashSetTreeSet
Inserted elements are in random orderMaintains the elements in the sorted order
Can able to store null objectsCouldn’t store null objects
Performance is fastPerformance is slow


Difference between Iterator and ListIterator?

We can use Iterator to traverse a Set or a List or a Map. But ListIterator can only be used to traverse a List only. Other differences can be listed as below.
You can –
  1. iterate backwards.
  2. obtain the index at any point.
  3. add a new value at any point.
  4. set a new value at that point.
e.g.
List names = new ArrayList();
names.add("Alex");
names.add("Bob");
names.add("Charles");
System.out.println(names);
ListIterator listIterator = names.listIterator();
//Add a value at any place using ListIterator
while(listIterator.hasNext()){
    listIterator.next();
    listIterator.add("Lokesh");
}
System.out.println(names);
listIterator = names.listIterator();
//Set a value at any place using ListIterator
while(listIterator.hasNext()){
    listIterator.next();
    listIterator.set("John");
}
System.out.println(names);
Output:
[Alex, Bob, Charles]
[Alex, Lokesh, Bob, Lokesh, Charles, Lokesh]
[John, John, John, John, John, John]

Clearly, I am able to add elements at random places in list while iterating over it – and similarily I can change any element as well. Using Iterator, it is not possible.


Q #22) Difference between HashSet and TreeSet.














Collection : Quick brush up 





Question 1 : What is the difference between fail-safe and fail fast iterator ?

https://stackoverflow.com/questions/17377407/what-are-fail-safe-fail-fast-iterators-in-java


Question 2 : What is copyonWriteArrayList ?



https://www.geeksforgeeks.org/copyonwritearraylist-in-java/

https://www.journaldev.com/1289/copyonwritearraylist-java









https://www.protechtraining.com/bookshelf/java_fundamentals_tutorial/generics_collections




Question 1:Collection implements which interfaces ?



Collection classes implements
·       java.util.RandomAccess
·       java.lang.Cloneable
·       java.io.Serializable marker interfaces
which provides special ability to these Collection classes at run time by JVM
1.    Random Access: to access any random element/objects with same speed
2.   Cloneable: to create a duplicate object or to clone an object


3.   Serializable: to transfer objects across network





Question 1:Difference between abstract class & interface? Why can't we create object of abstract class?

  1. Queue & PriorityQueue 

MethodDescription
boolean add(object)It is used to insert the specified element into this queue and return true upon success.
boolean offer(object)It is used to insert the specified element into this queue.
Object remove()It is used to retrieves and removes the head of this queue.
Object poll()It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.
Object element()It is used to retrieves, but does not remove, the head of this queue.
Object peek()It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

  1. Deque & ArrayDeque


Methods of Java Deque Interface

MethodDescription
boolean add(object)It is used to insert the specified element into this deque and return true upon success.
boolean offer(object)It is used to insert the specified element into this deque.
Object remove()It is used to retrieves and removes the head of this deque.
Object poll()It is used to retrieves and removes the head of this deque, or returns null if this deque is empty.
Object element()It is used to retrieves, but does not remove, the head of this deque.
Object peek()It is used to retrieves, but does not remove, the head of this deque, or returns null if this deque is empty.





import java.util.*;   
 public class DequeExample {   
 public static void main(String[] args) {   
   Deque deque=new ArrayDeque();   
   deque.offer("arvind");   
   deque.offer("vimal");   
   deque.add("mukul");   
   deque.offerFirst("jai");   
   System.out.println("After offerFirst Traversal...");   
   for(String s:deque){   
     System.out.println(s);   
   }   
   //deque.poll();   
   //deque.pollFirst();//it is same as poll()   
   deque.pollLast();   
   System.out.println("After pollLast() Traversal...");   
   for(String s:deque){   
     System.out.println(s);   
   }   
 }   
 }  

  1. Java EnumSet
import java.util.*;   
 enum days {   
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY   
 }   
 public class EnumSetExample {   
  public static void main(String[] args) {   
   Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);   
   // Traversing elements   
   Iterator iter = set.iterator();   
   while (iter.hasNext())   
    System.out.println(iter.next());   
  }   
 }   
  1. Java EnumMap
 import java.util.*;   
 enum days {   
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY   
 }   
 public class EnumSetExample {   
  public static void main(String[] args) {   
   Set set1 = EnumSet.allOf(days.class);   
    System.out.println("Week Days:"+set1);   
    Set set2 = EnumSet.noneOf(days.class);   
    System.out.println("Week Days:"+set2);     
  }   
 }  
  1. We never thought of properties as collection  lol;)

  2. Properties class in Java


MethodDescription
public void load(Reader r)loads data from the Reader object.
public void load(InputStream is)loads data from the InputStream object
public String getProperty(String key)returns value based on the key.
public void setProperty(String key,String value)sets the property in the properties object.
public void store(Writer w, String comment)writers the properties in the writer object.
public void store(OutputStream os, String comment)writes the properties in the OutputStream object.
storeToXML(OutputStream os, String comment)writers the properties in the writer object for generating xml document.
public void storeToXML(Writer w, String comment, String encoding)writers the properties in the writer object for generating xml document with specified encoding.

No comments:

Post a Comment