Collections Interview Question: 1. What Is The Collection API?
Collections Interview Question: 1. What Is The Collection API?
Interview Question
Collections
Interview Question
But an implementation class can naver be sorted and unordered because sorting is
specific type of ordering.
Ordered: if any collection is ordered, it means you can iterate the collection in a specfic
order (non-randam).
e.g.
Hashtable collection is not ordered.
ArrayList keeps the order established by the elements index position.
LinkedHashSet keeps the order established by insertion so the last elemented inserted is
the last element in the LinkedHashSet.
Sorted: A sorted collection means that the order in the collection is determined
according to some rule or rules, known as sorted order.
Collections
Interview Question
ArrayList
Vector
framework.
part
of
Java
Collection(1.2
Version).
Methods
of
ArrayList
are
not
synchronized.
(thread-safe)
increment size.
increment size.
Collections
Interview Question
Output:
Collection.synchronizedList(List list);
Collections
Interview Question
Collection.synchronizedMap(Map map);
Collection.synchronizedCollection(Collection c);
9.
If an Employee class is present and its objects are added into an ArrayList.
Now I want the list to be sorted on the basis of employee age of Employe
class. What are the steps?
Collections
Interview Question
Collections
Interview Question
@Override
public int compareTo(Object e) {
return (this.age > ((Employee)e).age ) ? 1 : 0 ;
}
}
ComparableDemo.java
Collections
Interview Question
e2.setId(3L);
e2.setName("Arun3");
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
Collections.sort(employeeList);
Collections
Interview Question
iterator.hasNext();) {
10.If an Employee class is in jar file. And you dont have access of its source
code, and its objects are added into an ArrayList. Now I want the list to be
sorted on the basis of the employee age of Employee class. How you will
achive that?
In above scenario, since we dont have access of Employee class, so comparable
interface cant be implement. So in this scenario, we will use Compartor.
1. Create Comparator class and override the compare(Object obj1, Object obj2)
2. Now call Collection.sort(List, Comparator) method and pass list as argument.
Below is implemented example
Collections
Interview Question
10
Collections
Interview Question
AgeComparator.java
@Override
public int compare(Object o1, Object o2) {
int emp1Age = ((Employee) o1).getAge();
int emp2Age = ((Employee) o2).getAge();
11
Collections
Interview Question
return 1;
else if (emp1Age < emp2Age)
return -1;
else
return 0;
}
NameComparator.java
@Override
public int compare(Object o1, Object o2) {
String emp1Name = ((Employee) o1).getName();
String emp2Name = ((Employee) o2).getName();
return emp1Name.compareTo(emp2Name);
}
12
Collections
Interview Question
ComparableDemo.java
Collections
Interview Question
e3.setAge(27);
e3.setId(2L);
e3.setName("Arun2");
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
14
Collections
Interview Question
HashMap
Hashtable
15
Collections
Interview Question
value.
HashMap
is
introduced
in
JDK
1.2
version
It is faster
It is slower.
calling
Map m =
Collections.synchronizedMap(hashmap)
HashMap can be traverse using Iterator.
16
Collections
Interview Question
17
Collections
Interview Question
2. To create an array the size should be known or initialized to same value. If not
initialized carefully there could be memory wastage. But in ArrayList is all about
dynamic creation and there is no wastage of memory.
22. When to use ArrayList or LinkedList?
LinkedList and ArrayList are two different implementations of the List interface. But
there are some scenario where some times ArrayList is better and some times LinkedList
is better.
1. An ArrayList used array for internal storage. This means it fast for randam
access, because the array index gets you right to that element. But in case of
LinkedList you have only sequential search options.
2. But adding and deleting element from start or middel of the ArrayList is very
slow, because all elements will sift to forward or backword direction. In this
scenario Linked List is better than ArrayList.
3. ArrayList also gives the performance issue when the internal array fill up. Then
ArrayList has to create a new array and copy all the elements there. The ArrayList
has growth algorithm. After fill up the internal array, new array will create of size
((n*3)/2) + 1. But in case of LinkedList dont have such complexity.
23. Why is it preferred to declare:
List<String> list = new ArrayList<String>(); instead of ArrayList<String>
= new ArrayList<String>();?
It is prefored because
1. If later on code need to be changed from ArrayList to Vector then only at the
declaration place we can do that.
2. The most important one if a function is declared such that it takes list e.g. void
showDetails(List list); When the parameter is declared as List to the function it
can be called by passing any subclass of the List like ArrayList, LinkedList or
Vector making the function more flexible.
18
Collections
Interview Question
e.g.
public class ReadOnlyList {
list = Collections.unmodifiableList(list);
list.add(9);
}
}
19
Collections
Interview Question
Output:-
List : [4, 8, 6]
Exception in thread "main" java.lang.UnsupportedOperationException
at
java.util.Collections$UnmodifiableCollection.add(Collections.java:1018)
at operator.ReadOnlyList.main(ReadOnlyList.java:19)
Collections.unmodifiableMap(map);
For Collection
Collections.unmodifiableCollection(collection);
For Set
Collections.unmodifiableSet(set);
Collections
Interview Question
21
Collections
Interview Question
Enumeration em = vect.elements();
while (em.hasMoreElements()) {
String value = (String) em.nextElement();
System.out.println("value :" + value);
}
}
}
HashMap
LinkedHashMap
HashTable
HashTree
22
Collections
Interview Question
e.g.
TreeMapExample.java
map.put("Rohit", "BMW");
map.put("Deepak", "AUDI");
map.put("Pawan", "Sentro");
map.put("Kumar", "Maurti");
System.out.println("Map elements:");
//ordered by insertion order
for(String key : map.keySet()) {
System.out.println("Key/Value: " + key + "/" + map.get(key));
}
23
Collections
Interview Question
}
}
Output
Map elements:
Key/Value: Deepak/AUDI
Key/Value: Kumar/Maurti
Key/Value: Pawan/Sentro
Key/Value: Rohit/BMW
@Note - In above example you can see that TreeMap are arranged in sorted
order based on keys.
Example
Employee.java
24
Collections
Interview Question
25
Collections
Interview Question
AgeComperator.java
@Override
public int compare(Object o1, Object o2) {
int emp1Age = ((Employee) o1).getAge();
int emp2Age = ((Employee) o2).getAge();
26
Collections
Interview Question
}
}
TreeMapExample.java
27
Collections
Interview Question
map.put(e1, "TG01");
map.put(e2, "TG02");
map.put(e4, "TG03");
map.put(e3, "TG01");
Set sets = map.keySet();
for (Iterator iterator = sets.iterator(); iterator.hasNext();) {
Employee emp = (Employee) iterator.next();
System.out.println("Employee : Name : " +
emp.getName()
+ " Age : " + emp.getAge());
}
}
}
Output
Collections
Interview Question
Example
HashMapDemo.java
29
Collections
Interview Question
Output
Map elements:
Key : [ Rohit ] Yalue : [ BMW ]
30
Collections
Interview Question
35. Which data structure should be use when fast iteration and randam access
is required and why?
0-6
31