0% found this document useful (0 votes)
170 views

Collections Interview Question: 1. What Is The Collection API?

The document discusses various topics related to Java collections: 1. It describes the Collection API as a set of classes and interfaces that support operations on collections of objects, listing some common classes and interfaces. 2. It defines the differences between ordered, unordered, sorted, and unsorted collections and provides examples. 3. It compares the ArrayList and Vector classes and their differences in terms of synchronization, capacity, and performance. 4. It discusses how to sort a List based on employee age using both the Comparable and Comparator interfaces.

Uploaded by

adeshkumarkhare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
170 views

Collections Interview Question: 1. What Is The Collection API?

The document discusses various topics related to Java collections: 1. It describes the Collection API as a set of classes and interfaces that support operations on collections of objects, listing some common classes and interfaces. 2. It defines the differences between ordered, unordered, sorted, and unsorted collections and provides examples. 3. It compares the ArrayList and Vector classes and their differences in terms of synchronization, capacity, and performance. 4. It discusses how to sort a List based on employee age using both the Comparable and Comparator interfaces.

Uploaded by

adeshkumarkhare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Collections

Interview Question

1. What is the Collection API?


The collection API is set of classes and interfaces that support on operation on
collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet, and TreeMap.
Example of interfaces: Collection, Set, List, Map.
2. What is the Collection Hierarchy?
The Collection API is set of classes and interfaces are arrenged in following hierarchy.

Collections
Interview Question

3. Define Ordered, Unordered, Sorted and Unsorted flavors of Collection?


An implemented class can be in following flavours

Ordered and Sorted.

Ordered and Unsorted.

Unsorted and Unordered.

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

4. What is difference between ArrayList and Vector?


ArrayList and Vector both implements List interface and maintain insertion order. But
there are many differences between ArrayList and Vector class.

ArrayList

Vector

java.util.ArrayList was introduced with

java.util.Vector was introduced with first

java version 1.2 as part of collection

version of JDK (1.0 Version).

framework.

When Java Collection introduced then Vector


became

part

of

Java

Collection(1.2

Version).
Methods

of

ArrayList

are

not

All methods of Vector are synchronized

synchronized.

(thread-safe)

By default, ArrayList increases by half of

By default, Vector doubles the size of its

its size when its size is increased.

array when its size increased.

In case of ArrayList we cant specify

In case of Vector, we can specify the

increment size.

increment size.

ArrayList faster then Vector class.

As Vectors methods are synchronized so it is


slower then ArrayList.

By default, ArrayList capacity is 0

By default, Vector capacity is 10.

5. Which is better ArrayList or Vector?


It depends, if you want a speedy processing then go for ArrayList. If you want to go with
thread safety, then go for Vector.

6. How to set Initial Capacity and Increment size of Vector?


Below method is used to set Initial Capacity and Size of Vector.

Vector v = new Vector( int initialCapacity, int capacityIncrement);

Collections
Interview Question

public class VectorDemo {


public static void main(String[] args) {
Vector v = new Vector(4, 3);
System.out.println("Initial Capacity of Vector : "
+ v.capacity());
v.add(1);
v.add(2);
v.add(3);
v.add(4);
System.out.println("Capacity of Vector : "
+ v.capacity());
v.add(5);
System.out.println("Capacity of Vector : "
+ v.capacity());
}
}

Output:

Initial Capacity of Vector : 4


Capacity of Vector : 4
Capacity of Vector : 7

7. How can ArrayList syncronized without using Vector?


ArrayList can be syncronized using:

Collection.synchronizedList(List list);

Collections
Interview Question

8. How can other collection can be syncronized without using Vector?


As ArrayList other collection also can be syncronized using Collection class util method.

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?

In above scenerio, we will use Comparable interface.


1. Implement the Comparable interface for the Employee class and override the
compareTo(Object obj) method in which compare the employees age.
2. Now call the Collections.sort() method and pass list as arguments.

Below is implemented example


Employee.Java

public class Employee implements Comparable{

private Long id;


private String name;
private int age;

public Long getId() {


return id;

Collections
Interview Question

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
6

Collections
Interview Question

@Override
public int compareTo(Object e) {
return (this.age > ((Employee)e).age ) ? 1 : 0 ;

}
}

ComparableDemo.java

public class ComparableDemo {

public static void main(String[] args) {


List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setAge(30);
e1.setId(1L);
e1.setName("Arun4");

Employee e2 = new Employee();


e2.setAge(25);

Collections
Interview Question

e2.setId(3L);
e2.setName("Arun3");

Employee e3 = new Employee();


e3.setAge(27);
e3.setId(2L);
e3.setName("Arun2");

Employee e4 = new Employee();


e4.setAge(32);
e4.setId(4L);
e4.setName("Arun1");

employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);

Collections.sort(employeeList);

for (Iterator iterator = employeeList.iterator();


8

Collections
Interview Question

iterator.hasNext();) {

Employee employee = (Employee) iterator.next();

System.out.println("Id : " + employee.getId()


+ "Age : "
+ employee.getAge() + " name : "
+ employee.getName());
}
}
}

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

Employee.java (class is in jar)

public class Employee {


9

Collections
Interview Question

private Long id;


private String name;
private int age;

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

10

Collections
Interview Question

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

AgeComparator.java

public class AgeComparator implements Comparator {

@Override
public int compare(Object o1, Object o2) {
int emp1Age = ((Employee) o1).getAge();
int emp2Age = ((Employee) o2).getAge();

if (emp1Age > emp2Age)

11

Collections
Interview Question

return 1;
else if (emp1Age < emp2Age)
return -1;
else
return 0;
}

NameComparator.java

public class NameComparator implements Comparator {

@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

@Note Here, String classs compareTo() method is used in comparing the


name fields (which are String).

ComparableDemo.java

public class ComparableDemo {

public static void main(String[] args) {


List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee();
e1.setAge(30);
e1.setId(1L);
e1.setName("Arun4");

Employee e2 = new Employee();


e2.setAge(25);
e2.setId(3L);
e2.setName("Arun3");

Employee e3 = new Employee();


13

Collections
Interview Question

e3.setAge(27);
e3.setId(2L);
e3.setName("Arun2");

Employee e4 = new Employee();


e4.setAge(32);
e4.setId(4L);
e4.setName("Arun1");

employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);

Collections.sort(employeeList, new NameComparator());

for (Iterator iterator = employeeList.iterator();


iterator.hasNext();) {

Employee employee = (Employee) iterator.next();

14

Collections
Interview Question

System.out.println("Id : " + employee.getId()


+ "Age : "
+ employee.getAge() + " name : "
+ employee.getName());
}
}
}

11.What is difference between array and arraylist?


An ArrayList resizble, where as array is not. ArrayList is part of collection framework and
can be store any type of object. And array is collection of similar type of data items.
12.Can we limit the initial capacity of Vector in Java?
Yes, we can limit the initial capacity of Vector. We can construct an empty vector with
specified intial capacity.

Vector v = new Vector( int initialCapacity);

13. What is difference between HashMap and HashTable?


Both collection implements Map interface. Both collections stores value as key-value pair.
Both are using hashing technique to store unique key. The main difference between
them are

HashMap

Hashtable

It is non synchronized. It is not-thread safe

Hashtable is syncronized. It is thread safe. It

and cant be share between many threads

can be share between many threads.

without proper syncronised code.

15

Collections
Interview Question

HashMap allows one null key value and

Hashtable doesnt allows null key or null

multiple null values.

value.

HashMap

is

introduced

in

JDK

1.2

Hashtable is a legacy class.

version
It is faster

It is slower.

HashMap can be used as syncronized by

Hashtable is internally syncronized.

calling
Map m =
Collections.synchronizedMap(hashmap)
HashMap can be traverse using Iterator.

Hashtable can be traverse through Iterator


and Enumerator.

14. Iterator is an interface or class?


Iterator is an interface. Iterator takes the place of Enumeration in Java Collection
framework. Its found in java.util package.
15. How many methods are in Iterator interface?
There are only three methods in Iterator interface.

Public Boolean hashNext()

Public Object next()

Public void remove()

16. What is ListIterator interface?


ListIterator interface is derived from Iterator interface and comes with more method
than Iterator interface.

public interface ListIterator<E> extends Iterator<E>


ListIterator interface is used to traverse the element in backword and forward direction.

16

Collections
Interview Question

17. What are commonly used method in ListIterator interface?


Below are the commonly methods in ListIterator interface
1. public boolean hasNext()
2. public Object next()
3. public boolean hasPrevious()
4. public Object previous()

18. what is fail-fast(ConcurrentModificationException)?


While iteration is going with iterators, modification with collections object cant be done
like additions or deletion etc.
19. What is difference between Iterator and ListIterator?
ListIterator is just like iterator, it provides traverse in both direction(Forward and
Backword direction).
20. Which all classes implement Set interface?
A Set is a collection that contains no duplicate elements. HashSet, SortedSet,
LinkedHashSet, and TreeSet are commonly implementation class of Set interface.

21. What is difference between Arrays and ArrayList?


Following are below differences between Arrays and ArrayList
1. Arrays are created of fix size, whereas ArrayList is of not fix.

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

24. How to make a List(ArrayList, LinkedList, Vector) readonly?


Any List implemenation class can made read only using Collections.unmodifableList(list).
This method returns new list. If any user try to perform add operation in new list,
UnSupportedOperationException will throw.

e.g.
public class ReadOnlyList {

public static void main(String[] args) {

List list = new ArrayList();


list.add(4);
list.add(8);
list.add(6);

System.out.println("List : " + list );

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)

25. How to make other collections read only?


As List implementation class, other collections also can be made read only by following
way
For Map

Collections.unmodifiableMap(map);

For Collection

Collections.unmodifiableCollection(collection);

For Set
Collections.unmodifiableSet(set);

26. Which data structure HashSet implements internally?


HashSet implements HashMap internally to store data. The data passed to HashSet to
store as key in HashMap with Dummy Value.

public boolean add(E e) {


return map.put(e, PRESENT)==null;
}
And PRESENT is defined as
20

Collections
Interview Question

// Dummy value to associate with an Object in the backing Map


private static final Object PRESENT = new Object();

27. What is Enumeration interface?


The Enumeration interface allows you to iterate all the elements of a collection. Iterating
through Enumeration is similar to iterating through an Iterator. However, there is no
removal support with Enumeration.
Enumeration interface has two methods
1. boolean hashMoreElements()
2. Object nextElement()
28. What is difference between Enumeration and Iterator interface?
Enumeration is used whenever we want to make a collection objects as read-only. There
is no removal support with Enumeration.
29. How to use Enumeration for iterate through all the elements of collection?
Below is example for Enumeration
EnumerationExample.java

public class EnumerationExample {

public static void main(String[] args) {


Vector vect = new Vector();
vect.add("Rohit");
vect.add("Pawan");
vect.add("Kumar");

21

Collections
Interview Question

Enumeration em = vect.elements();

while (em.hasMoreElements()) {
String value = (String) em.nextElement();
System.out.println("value :" + value);
}
}
}

30. What are the main implementation class of Map interface?


The main implemenation of Map interface are

HashMap

LinkedHashMap

HashTable

HashTree

22

Collections
Interview Question

31. What is TreeMap?

TreeMap is an ordered and sorted map

Doesnt allow keys duplicates

It doesnt allows null value

Can iterate through the TreeMap in assending order or in decending order


according to natural order of the element.

e.g.
TreeMapExample.java

public class TreeMapExample {

public static void main(String[] args) {


TreeMap<String, String> map = new TreeMap<String, String>();

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.

32. How to create TreeMap with custom order?


TreeMap with custom sorting order.

Map map = new TreeMap(Comperator comparator);

Example
Employee.java

public class Employee {


private Long id;
private String name;
private int age;

24

Collections
Interview Question

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

25

Collections
Interview Question

public void setAge(int age) {


this.age = age;
}
}

AgeComperator.java

public class AgeComperator implements Comparator{

@Override
public int compare(Object o1, Object o2) {
int emp1Age = ((Employee) o1).getAge();
int emp2Age = ((Employee) o2).getAge();

if (emp1Age > emp2Age)


return 1;
else if (emp1Age < emp2Age)
return -1;
else
return 0;

26

Collections
Interview Question

}
}

TreeMapExample.java

public class TreeMapExample {


public static void main(String[] args) {
Map map = new TreeMap(new AgeComerator());
Employee e1 = new Employee();
e1.setAge(30);
e1.setId(1L);
e1.setName("Arun4");

Employee e2 = new Employee();


e2.setAge(25);
e2.setId(3L);
e2.setName("Arun3");

Employee e3 = new Employee();


e3.setAge(27);
e3.setId(2L);
e3.setName("Arun2");

27

Collections
Interview Question

Employee e4 = new Employee();


e4.setAge(32);
e4.setId(4L);
e4.setName("Arun1");

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

Employee : Name : Arun3 Age : 25


28

Collections
Interview Question

Employee : Name : Arun2 Age : 27


Employee : Name : Arun4 Age : 30
Employee : Name : Arun1 Age : 32

33. How will you remove duplicate elements in a List?


As already know, a Set cant contains duplicate value, so you just add elements of List
into Set, duplicate value will not be added.
34. What is a HashMap?
HashMap is an unordered and unsorted map, Like all Map implementation, HashMap
must have unique keys. The HashMap classes uses a Hashtable to implementation of
Map.
In sort,

The underlying data structure is Hashtable

Duplicate keys are not allowed duplicate values are allowed.

Insertion order is not preserved because insertion is based on hashcode of keys.

Heterogeneous objects are allowed for both keys and values.

null key is allowed only once.

null values are allowed multiple times.

Introduced in version 1.2

Example
HashMapDemo.java

public class HashMapDemo {

public static void main(String[] args) {

29

Collections
Interview Question

Map map = new HashMap();


map.put("Rohit", "BMW");
map.put("Deepak", "AUDI");
map.put("Pawan", "Sentro");
map.put("Kumar", "Maurti");
System.out.println("Map elements:");

Set set = map.entrySet();

for (Iterator iterator = set.iterator(); iterator.hasNext();) {


Map.Entry entry = (Map.Entry) iterator.next();
System.out.println("Key : [ " + entry.getKey() + " ] Yalue :
["
+ entry.getValue() + " ] ");
}
}
}

Output

Map elements:
Key : [ Rohit ] Yalue : [ BMW ]
30

Collections
Interview Question

Key : [ Kumar ] Yalue : [ Maurti ]


Key : [ Deepak ] Yalue : [ AUDI ]
Key : [ Pawan ] Yalue : [ Sentro ]

35. Which data structure should be use when fast iteration and randam access
is required and why?
0-6

31

You might also like