Java Collections Interview Questions
What is
HashMap and Map?
Map
is Interface and Hashmap is class that implements this interface.
What is the significance of ListIterator?
Or
What is the difference b/w Iterator and ListIterator?
Iterator : Enables
you to cycle through a collection in the forward direction only, for obtaining
or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the
modification of elements
Difference between HashMap and HashTable? Can we make hashmap synchronized?
1.
The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls. (HashMap allows null
values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe
is relevant from the context of iterators. If an iterator has been created on a
collection object and some other thread tries to modify the collection object
"structurally”, a concurrent modification exception will be thrown. It is
possible for other threads though to invoke "set" method since it
doesn’t modify the collection "structurally”. However, if prior to calling
"set", the collection has been modified structurally,
"IllegalArgumentException" will be thrown.
HashMap
can be synchronized by
Map
m = Collections.synchronizeMap(hashMap);
What is the difference between set and list?
A
Set stores elements in an unordered way and does not contain duplicate
elements, whereas a list stores elements in an ordered way but may contain
duplicate elements.
Difference between Vector and ArrayList? What is the Vector class?
Vector
is synchronized whereas ArrayList is not. The Vector class provides the
capability to implement a growable array of objects. ArrayList and Vector class
both implement the List interface. Both classes are implemented using
dynamically resizable arrays, providing fast random access and fast traversal.
In vector the data is retrieved using the elementAt() method while in
ArrayList, it is done using the get() method. ArrayList has no default size
while vector has a default size of 10. when you want programs to run in
multithreading environment then use concept of vector because it is
synchronized. But ArrayList is not synchronized so, avoid use of it in a
multithreading environment.
What is an Iterator interface? Is Iterator a Class or Interface?
What is its use?
The
Iterator is an interface, used to traverse through the elements of a
Collection. It is not advisable to modify the collection itself while
traversing an Iterator.
What is the Collections API?
The
Collections API is a set of classes and interfaces that support operations on
collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
What is the List interface?
The
List interface provides support for ordered collections of objects.
How can we access elements of a collection?
We
can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
What is the Set interface?
The
Set interface provides methods for accessing the elements of a finite
mathematical set. Sets do not allow duplicate elements.
What’s the difference between a queue and a stack?
Stack
is a data structure that is based on last-in-first-out rule (LIFO), while
queues are based on First-in-first-out (FIFO) rule.
What is the Map interface?
The
Map interface is used associate keys with values.
What is the Properties class?
The
properties class is a subclass of Hashtable that can be read from or written to
a stream. It also provides the capability to specify a set of default values to
be used.
Which implementation of the List interface provides for the
fastest insertion of a new element into the middle of the list?
a.
Vector
b. ArrayList
c. LinkedList
d. None of the above
b. ArrayList
c. LinkedList
d. None of the above
ArrayList
and Vector both use an array to store the elements of the list. When an element
is inserted into the middle of the list the elements that follow the insertion
point must be shifted to make room for the new element. The LinkedList is
implemented using a doubly linked list; an insertion requires only the updating
of the links at the point of insertion. Therefore, the LinkedList allows for
fast insertions and deletions.
How can we use hashset in collection interface?
This
class implements the set interface, backed by a hash table (actually a HashMap
instance). It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant over
time. This class permits the Null element.
This
class offers constant time performance for the basic operations (add, remove,
contains and size), assuming the hash function disperses the elements properly
among the buckets.
What are differences between Enumeration, ArrayList, Hashtable and
Collections and Collection?
Enumeration:
It is series of elements. It can be use to enumerate through the elements of a
vector, keys or values of a hashtable. You can not remove elements from
Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List'
group in collection. It permits all elements, including null. It is not thread
-safe.
Hashtable: It maps key to value. You can use non-null value for key or
value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on
collections.
Collection: It is the root interface in the collection hierarchy.
What is difference between array & arraylist?
An
ArrayList is resizable, where as, an array is not. ArrayList is a part of the
Collection Framework. We can store any type of objects, and we can deal with
only objects. It is growable. Array is collection of similar data items. We can
have array of primitives or objects. It is of fixed size. We can have multi
dimensional arrays.
Array: can store
primitive ArrayList: Stores
object only
Array: fix size ArrayList: resizable
Array: can have multi
dimensional
Array: lang
ArrayList: Collection
framework
Can you limit the initial capacity of vector in java?
Yes
you can limit the initial capacity. We can construct an empty vector with
specified initial capacity
public
vector(int initialcapacity)
What method should the key class of Hashmap override?
The
methods to override are equals() and hashCode().
What is the difference between Enumeration and Iterator?
The
functionality of Enumeration interface is duplicated by the Iterator interface.
Iterator has a remove() method while Enumeration doesn't. Enumeration acts as
Read-only interface, because it has the methods only to traverse and fetch the
objects, where as using Iterator we can manipulate the objects also like adding
and removing the objects.
So
Enumeration is used when ever we want to make Collection objects as Read-only.
1.What are the principle concepts of OOPS?
There are four principle
concepts upon which object oriented design and programming rest. They are:
- Abstraction
- Polymorphism
- Inheritance
- Encapsulation
(i.e.
easily remembered as A-PIE).
2.What is Abstraction?
Abstraction refers to the
act of representing essential features without including the background details
or explanations.
3.What is Encapsulation?
Encapsulation is a
technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from
directly altering or accessing the properties or methods of the encapsulated
object.
4.What is the difference between abstraction and encapsulation?
- Abstraction focuses
on the outside view of an object (i.e. the interface) Encapsulation (information
hiding) prevents clients from seeing it’s inside view, where the behavior
of the abstraction is implemented.
- Abstraction solves
the problem in the design side while Encapsulation is the
Implementation.
- Encapsulation is
the deliverables of Abstraction. Encapsulation barely talks about grouping
up your abstraction to suit the developer needs.
5.What is Inheritance?
- Inheritance
is the process by which objects of one class acquire the properties of
objects of another class.
- A
class that is inherited is called a superclass.
- The
class that does the inheriting is called a subclass.
- Inheritance
is done by using the keyword extends.
- The
two most common reasons to use inheritance are:
- To
promote code reuse
- To
use polymorphism
6.What is Polymorphism?
Polymorphism is briefly
described as "one interface, many implementations." Polymorphism is a
characteristic of being able to assign a different meaning or usage to
something in different contexts - specifically, to allow an entity such as a
variable, a function, or an object to have more than one form.
7.How does Java implement polymorphism?
(Inheritance, Overloading
and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
- In
some cases, multiple methods have the same name, but different formal
argument lists (overloaded methods).
- In
other cases, multiple methods have the same name, same return type, and
same formal argument list (overridden methods).
8.Explain the different forms of Polymorphism.
There are two types of polymorphism
one is Compile time polymorphism and the other is run time
polymorphism. Compile time polymorphism is method overloading. Runtime
time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
- Method
overloading
- Method
overriding through inheritance
- Method
overriding through the Java interface
9.What is runtime polymorphism or dynamic method dispatch?
In Java, runtime
polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time. In this
process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
10.What is Dynamic Binding?
Binding refers to the
linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated
with a given procedure call is not known until the time of the call at
run-time. It is associated with polymorphism and inheritance.
11.What is method overloading?
Method Overloading means
to have two or more methods with same name in the same class with different
arguments. The benefit of method overloading is that it allows you to implement
methods that support the same semantic operation but differ by argument number
or type.
Note:
Note:
- Overloaded
methods MUST change the argument list
- Overloaded
methods CAN change the return type
- Overloaded
methods CAN change the access modifier
- Overloaded
methods CAN declare new or broader checked exceptions
- A
method can be overloaded in the same class or in a subclass
12.What is method overriding?
Method overriding occurs
when sub class declares a method that has the same type arguments as a method
declared by one of its superclass. The key benefit of overriding is the ability
to define behavior that’s specific to a particular subclass type.
Note:
Note:
- The
overriding method cannot have a more restrictive access modifier than the
method being overridden (Ex: You can’t override a method marked public and
make it protected).
- You
cannot override a method marked final
- You
cannot override a method marked static
13.What are the differences between method overloading and method overriding?
|
Overloaded Method
|
Overridden Method
|
Arguments
|
Must change
|
Must not change
|
Return type
|
Can change
|
Can’t change except for covariant returns
|
Exceptions
|
Can change
|
Can reduce or eliminate. Must not throw new or broader checked
exceptions
|
Access
|
Can change
|
Must not make more restrictive (can be less restrictive)
|
Invocation
|
Reference type determines which overloaded version is
selected. Happens at compile time.
|
Object type determines which method is selected. Happens at
runtime.
|
14.Can overloaded methods be override too?
Yes, derived classes
still can override the overloaded methods. Polymorphism can still happen.
Compiler will not binding the method calls since it is overloaded, because it
might be overridden now or in the future.
15.Is it possible to override the main method?
NO, because main is a
static method. A static method can't be overridden in Java.
16.How to invoke a superclass version of an Overridden method?
To invoke a superclass
method that has been overridden in a subclass, you must either call the method
directly through a superclass instance, or use the super prefix in the subclass
itself. From the point of the view of the subclass, the super prefix provides
an explicit reference to the superclass' implementation of the method.
//
From subclass
super.overriddenMethod();
17.What is super?
super is a keyword which
is used to access the method or member variables from the superclass. If a
method hides one of the member variables in its superclass, the method can
refer to the hidden variable through the use of the super keyword. In the same
way, if a method overrides one of the methods in its superclass, the method can
invoke the overridden method through the use of the super keyword.
Note:
Note:
- You
can only go back one level.
- In
the constructor, if you use super(), it must be the very first code, and
you cannot access any this.xxx variables or methods to
compute its parameters.
18.How do you prevent a method from being overridden?
To prevent a specific
method from being overridden in a subclass, use the final modifier on the
method declaration, which means "this is the final implementation of this
method", the end of its inheritance hierarchy.
public final void exampleMethod() {
// Method statements
}
// Method statements
}
19.What is an Interface?
An interface is a
description of a set of methods that conforming implementing classes must have.
Note:
Note:
- You
can’t mark an interface as final.
- Interface
variables must be static.
- An
Interface cannot extend anything but another interfaces.
20.Can we instantiate an interface?
You can’t instantiate an
interface directly, but you can instantiate a class that implements an
interface.
21.Can we create an object for an interface?
Yes, it is always
necessary to create an object implementation for an interface. Interfaces
cannot be instantiated in their own right, so you must write a class that
implements the interface and fulfill all the methods defined in it.
22.Do interfaces have member variables?
Interfaces may have member variables, but these are
implicitly public, static, and final- in other words, interfaces can declare only constants, not
instance variables that are available to all implementations and may be used as
key references for method arguments for example.
23.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
24.What is a marker interface?
Marker interfaces are those which do not declare any required
methods, but signify their compatibility with certain operations. The java.io.Serializableinterface and Cloneable are typical marker interfaces. These do not contain any
methods, but classes must implement this interface in order to be serialized
and de-serialized.
25.What is an abstract class?
Abstract classes are
classes that contain one or more abstract methods. An abstract method is a
method that is declared, but contains no implementation.
Note:
Note:
- If
even a single method is abstract, the whole class must be declared
abstract.
- Abstract
classes may not be instantiated, and require subclasses to provide
implementations for the abstract methods.
- You
can’t mark a class as both abstract and final.
26.Can we instantiate an abstract class?
An abstract class can
never be instantiated. Its sole purpose is to be extended (subclassed).
27.What are the differences between Interface and Abstract class?
Abstract Class
|
Interfaces
|
An abstract class can provide complete, default code and/or
just the details that have to be overridden.
|
An interface cannot provide any code at all,just the
signature.
|
In case of abstract class, a class may extend only one
abstract class.
|
A Class may implement several interfaces.
|
An abstract class can have non-abstract methods.
|
All methods of an Interface are abstract.
|
An abstract class can have instance variables.
|
An Interface cannot have instance variables.
|
An abstract class can have any visibility: public, private,
protected.
|
An Interface visibility must be public (or) none.
|
If we add a new method to an abstract class then we have the
option of providing default implementation and therefore all the existing
code might work properly.
|
If we add a new method to an Interface then we have to track
down all the implementations of the interface and define implementation for
the new method.
|
An abstract class can contain constructors .
|
An Interface cannot contain constructors .
|
Abstract classes are fast.
|
Interfaces are slow as it requires extra indirection to find
corresponding method in the actual class.
|
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
- You
see that something in your design will change frequently.
- If
various implementations only share method signatures then it is better to
use Interfaces.
- you
need some classes to use some methods which you don't want to be included
in the class, then you go for the interface, which makes it easy to just
implement and make use of the methods defined in the interface.
Use Abstract Class when…
- If
various implementations are of the same kind and use common behavior or
status then abstract class is better to use.
- When
you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.
- Abstract
classes are an excellent way to create planned inheritance hierarchies.
They're also a good choice for nonleaf classes in class hierarchies.
29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract
methods can access a method that you declare as abstract.
30.Can there be an abstract class with no abstract methods in it?
Yes, there can be an
abstract class without abstract methods.
31.What is Constructor?
- A
constructor is a special method whose task is to initialize the object of
its class.
- It
is special because its name is the same as the class name.
- They
do not have return types, not even void and therefore
they cannot return values.
- They cannot
be inherited, though a derived class can call the base class
constructor.
- Constructor
is invoked whenever an object of its associated class is created.
32.How does the Java default constructor be provided?
If a class defined by the
code does not have any constructor, compiler will
automatically provide one no-parameter-constructor (default-constructor) for
the class in the byte code. The access modifier (public/private/etc.) of the
default constructor is the same as the class itself.
33.Can constructor be inherited?
No, constructor cannot be
inherited, though a derived class can call the base class constructor.
34.What are the differences between Contructors and Methods?
|
Constructors
|
Methods
|
Purpose
|
Create an instance of a class
|
Group Java statements
|
Modifiers
|
Cannot be abstract, final, native, static,
or synchronized
|
Can be abstract, final, native, static, or synchronized
|
Return Type
|
No return type, not even void
|
void or a valid return type
|
Name
|
Same name as the class (first letter is capitalized by
convention) -- usually a noun
|
Any name except the class. Method names begin with a lowercase
letter by convention -- usually the name of an action
|
this
|
Refers to another constructor in the same class. If used, it
must be the first line of the constructor
|
Refers to an instance of the owning class. Cannot be used by
static methods.
|
super
|
Calls the constructor of the parent class. If used, must be
the first line of the constructor
|
Calls an overridden method in the parent class
|
Inheritance
|
Constructors are not inherited
|
Methods are inherited
|
35.How are this() and super() used with constructors?
- Constructors
use this to refer to another constructor in the same
class with a different parameter list.
- Constructors
use super to invoke the superclass's constructor. If a
constructor uses super, it must use it in the first line;
otherwise, the compiler will complain.
36.What are the differences between Class Methods and Instance Methods?
Class Methods
|
Instance Methods
|
Class methods are methods which are declared as static. The
method can be called without creating an instance of the class
|
Instance methods on the other hand require an instance of the
class to exist before they can be called, so an instance of a class needs to
be created by using the new keyword.
Instance methods operate on specific instances of classes. |
Class methods can only operate on class members and not on
instance members as class methods are unaware of instance members.
|
Instance methods of the class can also not be called from
within a class method unless they are being called on an instance of that
class.
|
Class methods are methods which are declared as static. The
method can be called without creating an instance of the class.
|
Instance methods are not declared as static.
|
37.How are this() and super() used with constructors?
- Constructors
use this to refer to another constructor in the same
class with a different parameter list.
- Constructors
use super to invoke the superclass's constructor. If a
constructor uses super, it must use it in the first line; otherwise, the
compiler will complain.
38.What are Access Specifiers?
One of the techniques in
object-oriented programming is encapsulation. It concerns the
hiding of data in a class and making this class available only through methods.
Java allows you to control access to classes, methods, and fields via
so-called access specifiers..
39.What are Access Specifiers available in Java?
Java offers four access
specifiers, listed below in decreasing accessibility:
- Public- public classes,
methods, and fields can be accessed from everywhere.
- Protected- protected methods
and fields can only be accessed within the same class to which the methods
and fields belong, within its subclasses, and within classes of the same
package.
- Default(no
specifier)- If you do not set access to
specific level, then such a class, method, or field will be accessible
from inside the same package to which the class, method, or field belongs,
but not from outside this package.
- Private- private methods
and fields can only be accessed within the same class to which the methods
and fields belong. private methods and fields are not
visible within subclasses and are not inherited by subclasses.
Situation
|
public
|
protected
|
default
|
private
|
Accessible to class
from same package? |
yes
|
yes
|
yes
|
no
|
Accessible to class
from different package? |
yes
|
no, unless
it is a subclass
|
no
|
no
|
40.What is final modifier?
The final modifier
keyword makes that the programmer cannot change the value anymore. The actual
meaning depends on whether it is applied to a class, a variable, or a method.
- final Classes-
A final class cannot have subclasses.
- final Variables-
A final variable cannot be changed once it is initialized.
- final Methods-
A final method cannot be overridden by subclasses.
41.What are the uses of final method?
There are two reasons for
marking a method as final:
- Disallowing
subclasses to change the meaning of the method.
- Increasing
efficiency by allowing the compiler to turn calls to the method into
inline Java code.
42.What is static block?
Static block which
exactly executed exactly once when the class is first loaded into JVM. Before
going to the main method the static block will execute.
43.What are static variables?
Variables that have only
one copy per class are known as static variables. They are not attached to a
particular instance of a class but rather belong to a class as a whole. They
are declared by using the static keyword as a modifier.
static
type varIdentifier;
where, the name of the
variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
44.What is the difference between static and non-static variables?
A static variable is
associated with the class as a whole rather than with specific instances of a
class. Non-static variables take on unique values with each object instance.
45.What are static methods?
Methods declared with the
keyword static as modifier are called static methods or class methods. They are
so called because they affect a class as a whole, not a particular instance of
the class. Static methods are always invoked without reference to a particular
instance of a class.
Note:The use of a static method suffers from the following restrictions:
Note:The use of a static method suffers from the following restrictions:
- A
static method can only call other static methods.
- A
static method must only access static data.
- A
static method cannot reference to the current object using
keywords super or this.
46.What is an
Iterator ?
47.How do you traverse through a collection using its Iterator?
To use an iterator to
traverse through the contents of a collection, follow these steps:
48.How do you remove elements during Iteration?
Iterator also has a
method remove() when remove is called, the current
element in the iteration is deleted.
49.What is the difference between Enumeration and Iterator?
Note: So
Enumeration is used whenever we want to make Collection objects as Read-only.
50.How is ListIterator?
ListIterator is
just like Iterator, except it allows us to access the collection in either
the forward or backward direction and lets us modify an element
51.What is the List interface?
52.What are the main implementations of the List interface ?
The main
implementations of the List interface are as follows :
53.What are the advantages of ArrayList over arrays ?
Some of the advantages
ArrayList has over arrays are:
54.Difference between ArrayList and Vector ?
55.How to obtain Array
from an ArrayList ?
Array can be obtained
from an ArrayList using toArray() method on
ArrayList.
List arrayList = new ArrayList();
arrayList.add(…
Object a[] = arrayList.toArray();
56.Why insertion and
deletion in ArrayList is slow compared to LinkedList ?
57.Why are Iterators
returned by ArrayList called Fail Fast ?
Because, if list is
structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove or add methods, the iterator will
throw a ConcurrentModificationException. Thus, in the face of concurrent
modification, the iterator fails quickly and cleanly, rather than risking
arbitrary, non-deterministic behavior at an undetermined time in the future.
58.How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random
access, without inserting or removing elements from any place other than the
end, then ArrayList offers the optimal collection. If, however, you need to
frequently add and remove elements from the middle of the list and only
access the list elements sequentially, then LinkedList offers the better
implementation.
|
||||||||||||||||||||||||||||
59.What is the Set interface ?
60.What are the main Implementations of the Set
interface ?
The main implementations of the List interface are as follows:
61.What is a HashSet ?
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in
sorted order. The elements are sorted according to the natural order of
elements or by the comparator provided at creation time.
63.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all
of the elements in the EnumSet type that is specified, explicitly or
implicitly, when the set is created.
64.Difference between HashSet and TreeSet ?
65.What is a Map ?
66.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
67.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which
extends the Map interface. In a TreeMap the data will be sorted in ascending
order of keys according to the natural order for the key's class, or by the
comparator provided at creation time. TreeMap is based on the Red-Black tree
data structure.
68.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the
HashMap offers the best alternative. If, however, you need to traverse the
keys in a sorted order, then TreeMap is your better alternative. Depending
upon the size of your collection, it may be faster to add elements to a
HashMap, then convert the map to a TreeMap for sorted key traversal.
69.Difference between HashMap and Hashtable ?
Note: Only one NULL is allowed as a key in HashMap. HashMap
does not allow multiple keys to be NULL. Nevertheless, it can have multiple
NULL values.
70.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which
extends the Map interface. In a TreeMap the data will be sorted in ascending
order of keys according to the natural order for the key's class, or by the
comparator provided at creation time. TreeMap is based on the Red-Black tree
data structure.
71.What Are the different Collection Views That Maps Provide?
Maps Provide Three Collection Views.
72.What is a KeySet View ?
KeySet is a set returned by the keySet() method of
the Map Interface, It is a set that contains all the keys present in the Map.
73.What is a Values Collection View ?
Values Collection View is a collection returned by
the values() method of the Map Interface, It contains all the
objects present as values in the map.
74.What is an EntrySet View ?
Entry Set view is a set that is returned by
the entrySet() method in the map and contains Objects of type Map.
Entry each of which has both Key and Value.
75.How do you sort an ArrayList (or any list) of user-defined objects ?
Create an implementation of
the java.lang.Comparable interface that knows how to order your
objects and pass it to java.util.Collections.sort(List, Comparator).
76.What is the Comparable interface ?
The Comparable interface is used to sort collections and
arrays of objects using
the Collections.sort() and java.utils.Arrays.sort() methods
respectively. The objects of the class implementing the Comparable interface
can be ordered.
The Comparable interface in the generic form is written as
follows:
interface
Comparable<T>
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of thecompareTo() method is as follows:
int i =
object1.compareTo(object2)
77.What are the differences between the Comparable and Comparator interfaces ?
|
.What is an exception?
An exception is
an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.
2.What is error?
An Error indicates that
a non-recoverable condition has occurred that should not be caught. Error, a
subclass of Throwable, is intended for drastic problems, such as
OutOfMemoryError, which would be reported by the JVM itself.
3.Which is superclass of
Exception?
"Throwable", the
parent class of all exception related classes.
4.What are the advantages
of using exception handling?
Exception handling
provides the following advantages over "traditional" error
management techniques:
5.What are the types of
Exceptions in Java
There are two types of
exceptions in Java, unchecked exceptions and checked exceptions.
6.Why Errors are Not
Checked?
A unchecked exception
classes which are the error classes (Error and its
subclasses) are exempted from compile-time checking because they can occur at
many points in the program and recovery from them is difficult or impossible.
A program declaring such exceptions would be pointlessly.
7.Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and
its subclasses) are exempted from compile-time checking because, in the
judgment of the designers of the Java programming language, having to declare
such exceptions would not aid significantly in establishing the correctness
of programs. Many of the operations and constructs of the Java programming
language can result in runtime exceptions. The information available to a
compiler, and the level of analysis the compiler performs, are usually not
sufficient to establish that such run-time exceptions cannot occur, even
though this may be obvious to the programmer. Requiring such exception
classes to be declared would simply be an irritation to programmers.
8.Explain the significance of try-catch blocks?
Whenever the exception
occurs in Java, we need a way to tell the JVM what code to execute. To do
this, we use the try and catch keywords. The try is used to define a block of
code in which exceptions may occur. One or more catch clauses match a
specific exception to a block of code that handles it.
![]() 9.What is the use of finally block?
The finally block
encloses code that is always executed at some point after the try block,
whether an exception was thrown or not. This is right place to close files,
release your network sockets, connections, and perform any other cleanup your
code requires.
Note: If
the try block executes with no exceptions, the finally block is executed
immediately after the try block completes. It there was an exception thrown,
the finally block executes immediately after the proper catch block completes
10.What if there is a break or return statement in try block followed by finally block?
If there is a return
statement in the try block, the finally block executes right after the return
statement encountered, and before the return executes.
|
|||
11.Can we have the try block without catch block?
Yes, we can have the try block without catch block, but
finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause. 12.What is the difference throw and throws?
throws: Used in a method's signature if a method is
capable of causing an exception that it does not handle, so that callers of
the method can guard themselves against that exception. If a method is declared
as throwing a particular class of exceptions, then any other method that
calls it must either have a try-catch clause to handle that exception or must
be declared to throw that exception (or its superclass) itself.
A method that does not handle an exception it throws has to
announce this:
public void myfunc(int
arg) throws MyException {
… }
throw: Used to trigger an exception. The exception will
be caught by the nearest try-catch clause that can catch that type of
exception. The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
To throw an user-defined exception within a block, we use the
throw command:
throw new
MyException("I always wanted to throw an exception!");
13.How to create custom exceptions?
A. By extending the Exception class or one of its subclasses.
Example:
class MyException extends Exception {
public MyException() { super(); } public MyException(String s) { super(s); } }
14.What are the different ways to handle exceptions?
There are two ways to handle exceptions:
« Previous | 1 2 |Next »
|
Java Collections Framework contains most commonly asked Java
interview questions. A good understanding of Collections framework is required
to understand and leverage many powerful features of Java technology.
Java Collections framework is fundamental utility tools provided by Java that are not only topic of interview but also heavily used in java programming on all types of programs including web based and desktop applications.
Your knowledge of Java will be considered incomplete without a good working experience of collections API, therefore I highly recommend writing more code and experimenting with it as much as possible.
Here are few important practical collection framework interview questions that can be asked in a Java interview.
Java Collections framework is fundamental utility tools provided by Java that are not only topic of interview but also heavily used in java programming on all types of programs including web based and desktop applications.
Your knowledge of Java will be considered incomplete without a good working experience of collections API, therefore I highly recommend writing more code and experimenting with it as much as possible.
Here are few important practical collection framework interview questions that can be asked in a Java interview.
Java Interview Preparation
Tips
·
Part 3: Collections Framework Interview
Questions
What is Java
Collections API?
Java Collections framework API is a unified architecture for
representing and manipulating collections. The API contains Interfaces,
Implementations & Algorithm to help java programmer in everyday
programming. In nutshell, this API does 6 things at high level
·
Reduces programming efforts. - Increases program speed and
quality.
·
Allows interoperability among unrelated APIs.
·
Reduces effort to learn and to use new APIs.
·
Reduces effort to design new APIs.
·
Encourages & Fosters software reuse.
To be
specific, There are six collection java interfaces. The most basic interface is
Collection. Three interfaces extend Collection: Set, List, and SortedSet. The
other two collection interfaces, Map and SortedMap, do not extend Collection,
as they represent mappings rather than true collections.
What is an Iterator?
Some of the collection classes provide traversal of their
contents via a java.util.Iterator interface. This interface allows you to walk
through a collection of objects, operating on each object in turn. Remember
when using Iterators that they contain a snapshot of the collection at the time
the Iterator was obtained; generally it is not advisable to modify the
collection itself while traversing an Iterator.
What is the
difference between java.util.Iterator and java.util.ListIterator?
Iterator : Enables you to traverse through a collection in
the forward direction only, for obtaining or removing elements ListIterator :
extends Iterator, and allows bidirectional traversal of list and also allows the
modification of elements.
What is HashMap and Map?
Map is Interface which is part of Java collections framework.
This is to store Key Value pair, and Hashmap is class that implements that
using hashing technique.
Difference between HashMap and
HashTable? Compare Hashtable vs HashMap?
Both Hashtable & HashMap provide key-value access to
data. The Hashtable is one of the original collection classes in Java (also
called as legacy classes). HashMap is part of the new Collections Framework,
added with Java 2, v1.2. There are several differences between HashMap and
Hashtable in Java as listed below
·
The HashMap class is roughly equivalent to Hashtable, except that
it is unsynchronized and permits nulls. (HashMap allows null values as key and
value whereas Hashtable doesn’t allow nulls).
·
HashMap does not guarantee that the order of the map will remain
constant over time. But one of HashMap's subclasses is LinkedHashMap, so in the
event that you'd want predictable iteration order (which is insertion order by
default), you can easily swap out the HashMap for a LinkedHashMap. This
wouldn't be as easy if you were using Hashtable.
·
HashMap is non synchronized whereas Hashtable is synchronized.
·
Iterator in the HashMap is fail-fast while the enumerator for the
Hashtable isn't. So this could be a design consideration.
What does
synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at
one point of time. Any thread before performing an update on a hashtable will
have to acquire a lock on the object while others will wait for lock to be
released.
What is
fail-fast property?
At high level - Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
Why doesn't
Collection extend Cloneable and Serializable?
From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms
·
Synchronized means only one thread can modify a hash table at one
point of time. Basically, it means that any thread before performing an update
on a hashtable will have to acquire a lock on the object while others will wait
for lock to be released.
·
Fail-fast is relevant from the context of iterators. If an
iterator has been created on a collection object and some other thread tries to
modify the collection object "structurally”, a concurrent modification
exception will be thrown. It is possible for other threads though to invoke
"set" method since it doesn’t modify the collection
"structurally”. However, if prior to calling "set", the
collection has been modified structurally, "IllegalArgumentException"
will be thrown.
How can we make
Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
Where will you
use Hashtable and where will you use HashMap?
There are multiple aspects to this decision: 1. The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one. 2. If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.
Difference
between Vector and ArrayList? What is the Vector class?
Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences
·
Vector is a legacy class which has been retrofitted to implement
the List interface since Java 2 platform v1.2
·
Vector is synchronized whereas ArrayList is not. Even though
Vector class is synchronized, still when you want programs to run in
multithreading environment using ArrayList with Collections.synchronizedList()
is recommended over Vector.
·
ArrayList has no default size while vector has a default size of
10.
·
The Enumerations returned by Vector's elements method are not
fail-fast. Whereas ArraayList does not have any method returning Enumerations.
What is the Difference between Enumeration and Iterator interface?
Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
1.
Enumeration contains 2 methods namely hasMoreElements() &
nextElement() whereas Iterator contains three methods namely hasNext(),
next(),remove().
2.
Iterator adds an optional remove operation, and has shorter method
names. Using remove() we can delete the objects but Enumeration interface does
not support this feature.
3.
Enumeration interface is used by legacy classes. Vector.elements()
& Hashtable.elements() method returns Enumeration. Iterator is returned by
all Java Collections Framework classes. java.util.Collection.iterator() method
returns an instance of Iterator.
Why Java Vector
class is considered obsolete or unofficially deprecated? or Why should I always
use ArrayList over Vector?
You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That's almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don't need to. It's a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class. (Read details Deprecate Hashtable and Vector)
What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
What is the
difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.
Where will you use Vector and where will you
use ArrayList?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
What is the importance of hashCode() and equals()
methods? How they are used in Java?
The java.lang.Object has two methods defined in it. They are - public boolean equals(Object obj) public int hashCode(). These two methods are used heavily when objects are stored in collections. There is a contract between these two methods which should be kept in mind while overriding any of these methods. The Java API documentation describes it in detail. The hashCode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.HashMap. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn't necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().
What is the difference between Sorting
performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which
one to use and when?
Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.
What is java.util.concurrent BlockingQueue?
How it can be used?
Java has implementation of BlockingQueue available since Java 1.5. Blocking Queue interface extends collection interface, which provides you power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.
Set & List interface extend Collection,
so Why doesn't Map interface extend Collection?
Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun's FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.
Which implementation of the List interface
provides for the fastest insertion of a new element into the middle of the
list?
a. Vector b. ArrayList c. LinkedList ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
What is the difference between ArrayList and
LinkedList? (ArrayList vs LinkedList.)
java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:
·
ArrayList uses primitive object array for storing objects whereas
LinkedList is made up of a chain of nodes. Each node stores an element and the
pointer to the next node. A singly linked list only has pointers to next. A
doubly linked list has a pointer to the next and the previous element. This
makes walking the list backward easier.
·
ArrayList implements the RandomAccess interface, and LinkedList
does not. The commonly used ArrayList implementation uses primitive Object
array for internal storage. Therefore an ArrayList is much faster than a
LinkedList for random access, that is, when accessing arbitrary list elements
using the get method. Note that the get method is implemented for LinkedLists,
but it requires a sequential scan from the front or back of the list. This scan
is very slow. For a LinkedList, there's no fast way to access the Nth element
of the list.
·
Adding and deleting at the start and middle of the ArrayList is
slow, because all the later elements have to be copied forward or backward.
(Using System.arrayCopy()) Whereas Linked lists are faster for inserts and
deletes anywhere in the list, since all you do is update a few next and
previous pointers of a node.
·
Each element of a linked list (especially a doubly linked list)
uses a bit more memory than its equivalent in array list, due to the need for
next and previous pointers.
·
ArrayList may also have a performance issue when the internal
array fills up. The arrayList has to create a new array and copy all the
elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that
each time the buffer is too small it will create a new one of size (n*3)/2+1
where n is the number of elements of the current buffer. Hence if we can guess
the number of elements that we are going to have, then it makes sense to create
a arraylist with that capacity during object creation (using construtor new
ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.
Where will you use ArrayList and Where will
you use LinkedList? Or Which one to use when (ArrayList / LinkedList).
Below is a snippet from SUN's site. The Java SDK contains 2 implementations of the List interface - ArrayList and LinkedList. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.
What is
performance of various Java collection implementations/algorithms? What is Big
'O' notation for each of them ?
Each java collection implementation class have different performance for different methods, which makes them suitable for different programming needs.
Performance of Map interface implementations
Hashtable
An instance of Hashtable has two parameters that affect its
performance: initial capacity and load factor. The capacity is the number of
buckets in the hash table, and the initial capacity is simply the capacity at
the time the hash table is created. Note that the hash table is open: in the
case of a "hash collision", a single bucket stores multiple entries,
which must be searched sequentially. The load factor is a measure of how full
the hash table is allowed to get before its capacity is automatically
increased. The initial capacity and load factor parameters are merely hints to
the implementation. The exact details as to when and whether the rehash method
is invoked are implementation-dependent.
HashMap
This implementation provides constant-time [ Big O Notation
is O(1) ] performance for the basic operations (get and put), assuming the hash
function disperses the elements properly among the buckets. Iteration over
collection views requires time proportional to the "capacity" of the
HashMap instance (the number of buckets) plus its size (the number of key-value
mappings). Thus, it's very important not to set the initial capacity too high
(or the load factor too low) if iteration performance is important.
TreeMap
The TreeMap implementation provides guaranteed log(n) [ Big O
Notation is O(log N) ] time cost for the containsKey, get, put and remove
operations.
LinkedHashMap
A linked hash map has two parameters that affect its
performance: initial capacity and load factor. They are defined precisely as
for HashMap. Note, however, that the penalty for choosing an excessively high
value for initial capacity is less severe for this class than for HashMap, as
iteration times for this class are unaffected by capacity.
Performance of Set interface implementations
HashSet
The HashSet class offers constant-time [ Big O Notation is
O(1) ] performance for the basic operations (add, remove, contains and size),
assuming the hash function disperses the elements properly among the buckets.
Iterating over this set requires time proportional to the sum of the HashSet
instance's size (the number of elements) plus the "capacity" of the
backing HashMap instance (the number of buckets). Thus, it's very important not
to set the initial capacity too high (or the load factor too low) if iteration
performance is important.
TreeSet
The TreeSet implementation provides guaranteed log(n) time
cost for the basic operations (add, remove and contains).
LinkedHashSet
A linked hash set has two parameters that affect its
performance: initial capacity and load factor. They are defined precisely as
for HashSet. Note, however, that the penalty for choosing an excessively high
value for initial capacity is less severe for this class than for HashSet, as
iteration times for this class are unaffected by capacity.
Performance of List interface implementations
LinkedList
- Performance of get and remove methods is linear time [ Big
O Notation is O(n) ] - Performance of add and Iterator.remove methods is
constant-time [ Big O Notation is O(1) ]
ArrayList
- The size, isEmpty, get, set, iterator, and listIterator
operations run in constant time. [ Big O Notation is O(1) ] - The add operation
runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case
(since the array must be resized and copied) adding n elements requires linear
time [ Big O Notation is O(n) ] - Performance of remove method is linear time [
Big O Notation is O(n) ] - All of the other operations run in linear time [ Big
O Notation is O(n) ]. The constant factor is low compared to that for the
LinkedList implementation.
Can you think of a questions which is not part of this post? Please don't forget to share it with me in comments section & I will try to include it in the list.
Can you think of a questions which is not part of this post? Please don't forget to share it with me in comments section & I will try to include it in the list.
What is difference between
ArrayList and vector?
- Synchronization
- ArrayList is not thread-safe whereas Vector is thread-safe. In Vector
class each method like add(), get(int i) is surrounded with a synchronized
block and thus making Vector class thread-safe.
- Data growth -
Internally, both the ArrayList and Vector hold onto their contents using
an Array. When an element is inserted into an ArrayList or a Vector, the
object will need to expand its internal array if it runs out of room. A
Vector defaults to doubling the size of its array, while the ArrayList
increases its array size by 50 percent.
How can Arraylist be
synchronized without using Vector?
Arraylist can be synchronized using:
Collection.synchronizedList(List
list)
Other collections can be synchronized:
Collection.synchronizedMap(Map
map)
Collection.synchronizedCollection(Collection c)
If an Employee class is
present and its objects are added in an arrayList. Now I want the list to be
sorted on the basis of the employeeID of Employee class. What are the steps?
- Implement
Comparable interface for the Employee class and override the
compareTo(Object obj) method in which compare the employeeID
- Now call
Collections.sort() method and pass list as an argument.
How about when Employee
class is a jar file and you do not have access to its source code?
- Since Comparable
interface cannot be implemented, create Comparator and override the
compare(Object obj, Object obj1) method .
- Call
Collections.sort() on the list and pass Comparator as an argument.
What is difference between
HashMap and HashTable?
Both collections implements Map. Both
collections store value as key-value pairs. The key differences between the two
are
- HashMap is not
synchronized in nature but HashTable is.
- Another
difference is that iterator in the HashMap is fail-safe while the
enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is
structurally modified at any time after the iterator is created, in any
way except through the iterator's own remove method, the iterator will
throw a ConcurrentModificationException
- HashMap permits
null values and only one null key, while Hashtable doesn't allow key or
value as null.
What are the prominent
implementation of List interface?
The classes that implement List interface:
- ArrayList: It is
a resizable array implementation. The size of the ArrayList can be
increased dynamically also operations like add,remove and get can be
formed once the object is created. It also ensures that the data is
retrieved in the manner it was stored. The ArrayList is not thread-safe.
- Vector: It is
thread-safe implementation of ArrayList. The methods are wrapped around a
synchronized block.
- LinkedList: the
LinkedList also implements Queue interface and provide FIFO(First In First
Out) operation for add operation. It is faster if than ArrayList if it
performs insertion and deletion of elements from the middle of a list.
Which all classes
implement Set interface?
- SortedSet - It
is an interface which extends Set. A the name suggest , the interface
allows the data to be iterated in the ascending order or sorted on the
basis of Comparator or Comparable interface. All elements inserted into
the interface must implement Comparable or Comparator interface.
- TreeSet - It is
the implementation of SortedSet interface.This implementation provides
guaranteed log(n) time cost for the basic operations (add, remove and
contains). The class is not synchronized.
- HashSet: This
class implements the Set interface, backed by a hash table (actually a
HashMap instance). It makes no guarantees as to the iteration order of the
set; in particular, it does not guarantee that the order will remain
constant over time. This class permits the null element. This class offers
constant time performance for the basic operations (add, remove, contains
and size), assuming the hash function disperses the elements properly
among the buckets
What is difference between
List and a Set?
- List can contain
duplicate values but Set doesnt allow. Set allows only to unique
elements.
- List allows
retrieval of data to be in same order in the way it is inserted but Set
doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
What is difference between
Arrays and ArrayList ?
- Arrays are
created of fix size whereas ArrayList is of not fix size. It means that
once array is declared as:
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
- Also the size of
array cannot be incremented or decremented. But with ArrayList the size is
variable. Once the array is created elements cannot be added or
deleted from it. But with ArrayList the elements can be added and deleted
at runtime.
List list =
new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
- ArrayList is one
dimensional but array can be multidimensional.
int[][][]
intArray= new int[3][2][1]; // 3 dimensional array
- To create an
array the size should be known or initialized to some value. If
not initialized carefully there could me memory wastage. But arrayList is
all about dynamic creation and there is no wastage of memory.
When to use ArrayList or
LinkedList ?
Adding new elements is pretty fast for either
type of list. For the ArrayList, doing random lookup using
"get" is fast, but for LinkedList, it's slow. It's slow because
there's no efficient way to index into the middle of a linked list. When removing
elements, using ArrayList is slow. This is because all remaining elements in
the underlying array of Object instances must be shifted down for each remove
operation. But here LinkedList is fast, because deletion can be done simply by
changing a couple of links. So an ArrayList works best for cases where you're
doing random access on the list, and a LinkedList works better if you're doing
a lot of editing in the middle of the list.
Consider a scenario. If an
ArrayList has to be iterated to read data only, what are the possible ways and
which is the fastest?
It can be done in two ways, using for loop or
using iterator of ArrayList. The first option is faster than using iterator.
Because value stored in arraylist is indexed access. So while accessing the
value is accessed directly as per the index.
Now another question with
respect to above question is if accessing through iterator is slow then why do
we need it and when to use it.
For loop does not allow the updation in the
array(add or remove operation) inside the loop whereas Iterator does. Also
Iterator can be used where there is no clue what type of collections will be
used because all collections have iterator.
Which design pattern
Iterator follows?
It follows Iterator design pattern. Iterator
Pattern is a type of behavioral pattern. The Iterator pattern is one, which
allows you to navigate through a collection of data using a common interface
without knowing about the underlying implementation. Iterator should be
implemented as an interface. This allows the user to implement it anyway its
easier for him/her to return data. The benefits of Iterator are about their
strength to provide a common interface for iterating through collections
without bothering about underlying implementation.
Example of Iteration design pattern -
Enumeration The class java.util.Enumeration is an example of the Iterator
pattern. It represents and abstract means of iterating over a collection of
elements in some sequential order without the client having to know the
representation of the collection being iterated over. It can be used to provide
a uniform interface for traversing collections of all kinds.
Is it better to have a
HashMap with large number of records or n number of small hashMaps?
It depends on the different scenario one is
working on:
- If the objects
in the hashMap are same then there is no point in having different hashmap
as the traverse time in a hashmap is invariant to the size of the Map.
- If the objects
are of different type like one of Person class , other of Animal class etc
then also one can have single hashmap but different hashmap would score
over it as it would have better readability.
Why is it preferred to
declare: List<String> list = new ArrayList<String>(); instead of
ArrayList<String> = new ArrayList<String>();
It is preferred because
- If later on code
needs to be changed from ArrayList to Vector then only at the declaration
place we can do that.
- 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 List like ArrayList,Vector,LinkedList making the function more
flexible
What is difference between
iterator access and index access?
- Index based
access allow access of the element directly on the basis of index. The
cursor of the data structure can directly goto the 'n' location and get
the element. It does not traverse through n-1 elements.
- In Iterator
based access, the cursor has to traverse through each element to get the
desired element.So to reach the 'n'th element it need to traverse through
n-1 elements.
- Insertion,updation
or deletion will be faster for iterator based access if the operations are
performed on elements present in between the datastructure.
- Insertion,updation
or deletion will be faster for index based access if the operations are
performed on elements present at last of the datastructure.
- Traversal or
search in index based datastructure is faster.
- ArrayList is
index access and LinkedList is iterator access.
How to sort list in reverse order?
To sort the elements of the List in the
reverse natural order of the strings, get a reverse Comparator from the
Collections class with reverseOrder(). Then, pass the reverse Comparator to the
sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)
Can a null element added
to a Treeset or HashSet?
A null element can be added only if the
TreeSet contains one element because when a second element is added then as per
set definition a check is made to check duplicate value and
comparison with null element will throw NullPointerException. HashSet is
based on hashMap and can contain null element.
How to sort list of
strings - case insensitive?
using Collections.sort(list,
String.CASE_INSENSITIVE_ORDER);
How to make a List
(ArrayList,Vector,LinkedList) read only?
A list implemenation can be made read only
using Collections.unmodifiableList(list). This method returns a new list. If a
user tries to perform add operation on the new list;
UnSupportedOperationException is thrown.
What is ConcurrentHashMap?
A concurrentHashMap is thread-safe
implementation of Map interface. In this class put and remove method are
synchronized but not get method. This class is different from Hashtable in
terms of locking; it means that hashtable use object level lock but this class
uses bucket level lock thus having better performance.
Which is faster to iterate
LinkedHashSet or LinkedList?
LinkedList.
Which data structure HashSet
implements
HashSet implements hashmap internally to
store the data. The data passed to hashset is stored as key in hashmap with
null as value.
Arrange in the order of
speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap
HashMap is fastest, ConcurrentHashMap,
Collections.synchronizedMap, HashTable.
What is identityHashMap?
The IdentityHashMap uses == for equality
checking instead of equals(). This can be used for both performance reasons, if
you know that two different elements will never be equals and for preventing
spoofing, where an object tries to imitate another.
What is WeakHashMap?
A hashtable-based Map implementation with
weak keys. An entry in a WeakHashMap will automatically be removed when its key
is no longer in ordinary use. More precisely, the presence of a mapping for a
given key will not prevent the key from being discarded by the garbage
collector, that is, made finalizable, finalized, and then reclaimed. When a key
has been discarded its entry is effectively removed from the map, so this class
behaves somewhat differently than other Map implementations.
No comments:
Post a Comment