Java Collection Flashcards

1
Q

What is the difference between Collection and Collections Framework in Java?

A

In Java, a Collection is an object that contains multiple elements of
same type in a single unit. These multiple elements can be accessed through one Collection object.
In Java Collections Framework is a library that provides common architecture for creating, updating and accessing different types of
collections.
In Collections framework there are common methods that are frequently used by developers for working on a Collection
object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the main benefits of

Collections Framework in Java?

A

Reusability: Java Collections Framework provides
common classes and utility methods than can be used with
different types of collections. This promotes the reusability
of the code. A developer does not have to re-invent the
wheel by writing the same method again.
2. Quality: Using Java Collection Framework improves the
program quality, since the code is already tested and used
by thousands of developers.
3. Speed: Most of programmers report that their development
speed increased since they can focus on core logic and use
the generic collections provided by Java framework.
4. Maintenance: Since most of the Java Collections
framework code is open source and API documents is
widely available, it is easy to maintain the code written
with the help of Java Collections framework. One
developer can easily pick the code of previous developer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the root interface of Collection hierarchy in Java?

A

The root interface of Collection hierarchy in Java is Collection interface.
But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.
Iterable interface is present in java.lang package but Collection interface is present in java.util package.

Oracle Java API docs mention that Collection interface is a member of the Java Collections framework. Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs. Due to this Collection interface is the root of Collections Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the main differences between Collection and Collections?

A

Type: Collection is an interface in Java. Collections is a class.

Features: Collection interface provides basic features of data structure to List, Set and Queue interfaces. Collections is a utility class to sort and synchronize collection elements. It has polymorphic algorithms to operate on collections.

Method Type: Most of the methods in Collection are at instance level. Collections class has mainly static methods
that can work on an instance of Collection.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the Thread-safe classes in Java Collections framework?

A
Stack
Properties
Vector
Hashtable
BlockingQueue
ConcurrentMap
ConcurrentNavigableMap
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How will you efficiently remove elements while iterating a Collection?

A

The right way to remove elements from a collection while iterating is by using ListIterator.remove() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How will you convert a List to a Set?

A

Option 1: Use HashSet
Set mySet = new HashSet(myList);
In this case we put a list into a HashSet. Internally hashCode()
method is used to identify duplicate elements.

Option 2: Use TreeSet
In this case we use our own comparator to find duplicate objects.
Set mySet = new TreeSet(myComparator);
mySet.addAll(myList);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How will you remove duplicate elements from an ArrayList?

A

Option 1: Use Set
If ordering of elements is not important then we just put the elements of ArrayList in a HashSet and then add them back to the ArrayList.

Option 2: Use LinkedHashSet
If ordering of elements is important then we put the elements of ArrayList in a LinkedHashSet and then add them back to the ArrayList.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you maintain a Collection with elements in Sorted order?

A

Using TreeSet
By providing custom comparator inside the collection
Collections.sort
PriorityQueue

The main difference between PriorityQueue and
Collections.sort() is that PriorityQueue maintains a queue in Order
all the time, but we can only retrieve head element from queue. We
cannot access the elements of PriorityQueue in Random order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the differences between
the two data structures: a Vector and
an ArrayList?

A

Synchronization: Vector is synchronized, but the ArrayList is not synchronized. So an ArrayList has faster operations
than a Vector.

Data Growth: Internally both an ArrayList and Vector use an array to store data. When an ArrayList is almost full it increases its size by 50% of the array size. Whereas a
Vector increases it by doubling the underlying array size.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

In which scenario, LinkedList is better than ArrayList in Java?

A

ArrayList is more popular than LinkedList in Java due to its ease of use and random access to elements feature.

But LinkedList is better in the scenario when we do not need random access to elements or there are a lot of insertion, deletion of
elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the differences between a List and Set collection in Java?

A

Order: List collection is an ordered sequence of elements. A Set is just a distinct collection of elements that is unordered.

Positional Access: When we use a List, we can specify where exactly we want to insert an element. In a Set there is no order, so we can insert element anywhere without
worrying about order.

Duplicate: In a List we can store duplicate elements. A Set can hold only unique elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the differences between a HashSet and TreeSet collection in Java?

A

Ordering: In a HashSet elements are stored in a random order. In a TreeSet, elements are stored according to natural ordering.
Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.

Performance: HashSet performs basic operations like add(), remove(), contains(), size() etc in a constant size time. A TreeSet performs these operations at the order of
log(n) time.

Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc .

Internal Structure: a HashMap in Java internally backs a HashSet. A NavigableMap backs a TreeSet internally.

Features: A TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In Java, how will you decide when to use a List, Set or a Map collection?

A

If we want a Collection that does not store duplicate values, then we use a Set based collection.

If we want to frequently access elements operations based on an index value then we use a List based collection. E.g. ArrayList

If we want to maintain the insertion order of elements in a collection then we use a List based collection.

For fast search operation based on a key, value pair, we use a HashMap based collection.

If we want to maintain the elements in a sorted order, then we use a TreeSet based collection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the differences between a HashMap and a Hashtable in Java?

A

Synchronization: HashMap is not a synchronized collection. If it is used in multi-thread environment, it may not provide thread safety. A Hashtable is a synchronized collection. Not more than one thread can access a Hashtable at a given moment of time. The thread that works on Hashtable acquires a lock on it and it makes other threads wait till its work is completed.

Null values: A HashMap allows only one null key and any number of null values. A Hashtable does not allow null keys and null values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the differences between a HashMap and a TreeMap?

A

Order: A HashMap does not maintain any order of its keys. In a HashMap there is no guarantee that the element inserted first will be retrieved first.
In a TreeMap elements are stored according to natural
ordering of elements. A TreeMap uses compareTo()
method to store elements in a natural order.

A HashMap uses Hashing internally. A TreeMap internally uses Red-Black tree implementation.

A HashMap can store one null key and
multiple null values. A TreeMap can not contain null key but it may contain multiple null values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the differences
between Comparable and
Comparator?

A

In Comparable, we can only create one sort
sequence. In Comparator we can create multiple sort sequences.

 Comparator interface in Java has
method public int compare (Object o1, Object o2) that returns a negative integer, zero, or a positive integer when the object o1 is less than, equal to, or greater than the object o2. A Comparable interface has method public
int compareTo(Object o) that returns a negative integer, zero, or a positive integer when this object is less than, equal to, or greater than the object o
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

In Java, what is the purpose of Properties file?

A

A Properties file in Java is a list of key-value pairs that can be parsed by java.util.Properties class.

Some of the uses are to store configuration, initial data, application options etc.
When we change the value of a key in a properties file, there is no need to recompile the Java application. So it provides benefit of
changing values at runtime

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the reason for overriding equals() method?

A
The equals() method in Object class is used to check whether two objects are same or not. If we want a custom implementation we can
override this method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does hashCode() method work in Java?

A

Object class in Java has hashCode() method. This method returns a hash code value, which is an integer.

And we use the hascode generated as a key inside the any data structure that is going to implement the key value data structure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between Collections.emptyList() and creating new instance of Collection?

A

In both the approaches, we get an empty list. But Collections.emptyList() returns an Immutable list. We cannot add new elements to an Immutable empty list.

Collections.emptyList() works like Singleton pattern. It does not create a new instance of List. It reuses an existing empty list instance.

Therefore, Collections.emptylist() gives better performance if we need to get an emptyList multiple times.

22
Q

How will you copy elements from a Source List to another list?

A
Option 1: Use ArrayList constructor
ArrayList newList = new ArrayList(sourceList);

Option 2: Use Collection.copy()
ArrayList newList = new ArrayList
(sourceList.size());
Collections.copy(newList, sourceList);

23
Q

What are the Java Collection classes that implement List interface?

A
AbstractList
AbstractSequentialList
ArrayList
AttributeList
CopyOnWriteArrayList
LinkedList
RoleList
RoleUnresolvedList
Stack
Vector
24
Q

What are the Java Collection

classes that implement Set interface?

A
AbstractSet
ConcurrentSkipListSet
CopyOnWriteArraySet
EnumSet
HashSet
JobStateReasons
LinkedHashSet
TreeSet
25
Q

What is the difference between an Iterator and ListIterator in Java?

A

ListIterator can be used to traverse only a List. But Iterator can be used to traverse List, Set, and Queue etc.

An Iterator traverses the elements in one direction only. It just goes. ListIterator can traverse the elements in two directions i.e. backward as well as forward directions.

Iterator cannot provide us index of an element in the Data Structure. ListIterator provides us methods like nextIndex()
and previousIndex() to get the index of an element during traversal.
Iterator does not allow us to add an element to collection while traversing it. It throws
ConcurrentModificationException. ListIterator allows use to add an element at any point of time while traversing a list.

An existing element’s value cannot be replaced by using Iterator. ListIterator provides the method set(e) to replace
the value of last element returned by next() or previous() methods.

26
Q

What is the difference between

Iterator and Enumeration?

A

Enumeration is an older interface. Iterator is a newer interface.

Enumeration can only traverse legacy collections. Iterator can traverse both legacy as well as newer collections.

Enumeration does not provide remove() method. So we cannot remove any element during traversal. Iterator provides remove() method.

27
Q

What is the difference between an

ArrayList and a LinkedList data structure?

A

Data Structure: An ArrayList is an indexed based dynamic array. A LinkedList is a Doubly Linked List data structure.

Insertion: It is easier to insert new elements in a LinkedList, since there is no need to resize an array. Insertion in ArrayList is O(n), since it may require resizing of array and copying its contents to new array.

Remove elements: LinkedList has better performance in removal of elements than ArrayList.

Memory Usage: LinkedList uses more memory than ArrayList, since it has to maintain links for next and previous nodes as well.

Access: LinkedList is slower in accessing an element, since we have to traverse the list one by one to access the right location.

28
Q

What is the difference between a Set and a Map in Java?

A

Duplicate Elements: A Set does not allow inserting duplicate elements. A Map does not allow using duplicate keys, but it allows inserting duplicate values for unique
keys.

Null values: A Set allows inserting maximum one null value. In a Map we can have single null key at most and any number of null values.
Ordering: A Set does not maintain any order of elements. Some of sub-classes of a Set can sort the elements in an order like LinkedHashSet. A Map does not maintain any order of its elements. Some of its sub-classes like
TreeMap store elements of the map in ascending order of keys

29
Q

What is the use of a Dictionary class?

A

The Dictionary class in Java is used to store key-value pairs. Any
non-null object can be used for key or value. But we cannot insert a
null key or null object in Dictionary.
Dictionary class is deprecated now. So it should not be used in
newer implementations.

30
Q

What is the default size of load factor in a HashMap collection in Java?

A

Default value of load factor in a HashMap is 0.75.

31
Q

What is the significance of load factor in a HashMap in Java?

A

A HashMap in Java has default initial capacity 16 and the load factor is 0.75f (i.e. 75% of current map size). The load factor of a
HashMap is the level at which its capacity should be doubled.

For example, in a HashMap of capacity 16 and load factor .75. The capacity will become 32 when the HashMap is 75% full. Therefore,
after storing the 12th key– value pair (16 * .75 = 12) into HashMap, its capacity becomes 32

32
Q

What are the major differences between a HashSet and a HashMap?

A

Base class: A HashSet class implements the Set interface. Whereas a HashMap class implements the Map interface.

Storage: A HashSet is used to store distinct objects. AHashMap is used for storing key & value pairs, so that these can be retrieved by key later on.

Duplicate Elements: A HashSet does not allow storing duplicate elements. A HashMap also does not allow duplicate keys. But we can store duplicate values in a HashMap.

Null Elements: In a HashSet we can store a single null value. In a HashMap we can store single null key, but any number of null values.

Element Type: A HashSet contains only values of objects as its elements. Whereas a HashMap contains entries(key value pairs).

Iteration: By using an Iterator we can iterate a HashSet. But a HashMap has to be converted into Set for iteration.

33
Q

What are the similarities between a HashSet and a HashMap in Java?

A

Thread Safety: Both HashMap and HashSet are not synchronized collections. Therefore they are not good for thread-safe operations. To make these thread-safe we need
to explicitly use synchronized versions.

Order of Elements: None of these classes guarantee the order of elements. These are unordered collections.

34
Q

What is Hash Collision? How Java handles hash-collision in HashMap?

A

In a Hashing scenario, at times two different objects may have same HashCode but they may not be equal. Therefore, Java will face
issue while storing the two different objects with same HashCode in a HashMap. This kind of situation is Hash Collision.

There are different techniques of resolving or avoiding Hash Collision. But in HashMap, Java simply replaces the Object at old Key with new Object in case of Hash Collision.

35
Q

What is the difference between Queue and Stack data structures?

A

Stack is a LIFO data structure.

Queue is a FIFO data structure.

36
Q

How will you reverse a List in Java?

A

In Collections class, Java provides a method reverse(List list) that can be used to reverse a List.

37
Q

What is the difference between peek(), poll() and remove() methods of Queue interface in java?

A

If Queue is empty then poll() method returns null value. If Queue is empty then remove() method throws NoSuchElementException.

In a Java Queue, peek() method retrieves the head of Queue but it does not remove it. If queue is empty then peek() method returns
null value

38
Q

What is the difference between Array and ArrayList in Java?

A

Size
Performance
add() or get()- Constant time
Primitives- Arrays support primitive type data but Lists don’t

39
Q

How will you insert, delete and
retrieve elements from a HashMap
collection in Java?

A

Insert - put
Remove - remove
Retrieve - get

40
Q

What are the main differences between HashMap and ConcurrentHashMap in Java?

A

Synchronization: A HashMap is not synchronized. But a ConcurrentHashMap is a synchronized object.
Null Key: A HashMap can have one null key and any number of null values. A ConcurrentHashMap cannot have null keys or null values.
Multi-threading: A ConcurrentHashMap works well in a multi-threading environment.

41
Q

Why does Map interface not extend Collection interface in Java?

A

A Map is a collection objects. But Map interface is not compatible with Collection interface in Java.

42
Q

How is TreeMap class implemented in Java?

A

Internally, a TreeMap class in Java uses Red Black tree.

43
Q

What is an EnumSet in Java?

A

Use: It is mainly used with enum types.

In an EnumSet, null elements are not permitted. If we try to insert a null element it throws NullPointerException.

44
Q

What are the main Concurrent Collection classes in Java?

A
ArrayBlockingQueue
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentHashMap
ConcurrentLinkedDeque
ConcurrentLinkedQueue
LinkedBlockingQueue
LinkedBlockingDeque
PriorityBlockingQueue
45
Q

How will you convert a Collection to SynchronizedCollection in Java?

A

Collections.synchronizedCollection()

46
Q

How IdentityHashMap is

different from a regular Map in Java?

A

IndentityHashMap in Java implements Map interface. But it is not a general purpose implementation. It violates the general contract of Map interface by a different implementation of equals() method. In an IdentityHashMap, two keys k1 and k2 are equal if and only if
(k1==k2). (In a normal Map implementation (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

IdentityHashMap uses == sign but hashmap uses equals(obJ) which makes it slow.

47
Q

Is IdentityHashMap threadsafe?

A

The implementation of IdentityHashMap is not thread-safe, since its
methods are not synchronized.
The iterators returned by the iterator method of IdentityHashMap
are fail-fast. But the fail-fast behavior of an iterator cannot be
guaranteed.
Since the Iterator is fail-fast, it throws
ConcurrentModificationException.

48
Q

How can you make a Collection class read Only in Java?

A

Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Collections.unmodifiableCollection(Collection c)

49
Q

What is the difference between Synchronized Collection and Concurrent Collection?

A
The main difference is in performance. Concurrent collection classes have better performance than synchronized collection
classes because they lock only a portion of the class to achieve concurrency and thread-safety.
50
Q

hat is the scenario to use

ConcurrentHashMap in Java?

A

ConcurrentHashMap is more suited for scenarios where we have multiple reader threads and one writer thread. In this case map is locked only during the write operation.
If we have an equal number of reader and writer threads then ConcurrentHashMap performance is similar to a Hashtable or a
synchronized HashMap.

51
Q

Why we cannot create a generic array in Java?

A