Collections in
java is a framework that provides an architecture to store and manipulate the
group of objects.
All the
operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Collection
framework represents a unified architecture for storing and manipulating group
of objects. It has:
Algorithm
List
A List is an
ordered Collection (sometimes called a sequence). Lists may contain duplicate
elements. Elements can be inserted or accessed by their position in the list,
using a zero-based index.
There are 3 types
of List in java
ArrayList
LinkedList
Vector
Set
A Set is a
Collection that cannot contain duplicate elements. There are three main
implementations of Set interface: HashSet, TreeSet, and LinkedHashSet. HashSet,
which stores its elements in a hash table, is the best-performing
implementation; however it makes no guarantees concerning the order of
iteration. TreeSet, which stores its elements in a red-black tree, orders its
elements based on their values; it is substantially slower than HashSet.
LinkedHashSet, which is implemented as a hash table with a linked list running
through it, orders its elements based on the order in which they were inserted
into the set (insertion-order).
There are 3 types
of Set in java
HashSet
LinkedHashSet
TreeSet
Map
A Map is an
object that maps keys to values. A map cannot contain duplicate keys. There are
three main implementations of Map interfaces: HashMap, TreeMap, and
LinkedHashMap.
HashMap: it makes
no guarantees concerning the order of iteration
TreeMap: It
stores its elements in a red-black tree, orders its elements based on their
values; it is substantially slower than HashMap.
LinkedHashMap: It
orders its elements based on the order in which they were inserted into the set
(insertion-order).
There are 3 types of Map in java
HashMap
TreeMap
LinkedHashMap
Iterator/ListIterator
Both Iterator and
ListIterator are used to iterate through elements of a collection class. Using
Iterator we can traverse in one direction (forward) while using ListIterator we
can traverse the collection class on both the directions(backward and forward).
Iterator vs
ListIterator:
1) Iterator is
used for traversing List and Set both.
We can use
ListIterator to traverse List only, we cannot traverse Set using ListIterator.
2) We can
traverse in only forward direction using Iterator.
Using
ListIterator, we can traverse a List in both the directions (forward and
Backward).
3) We cannot
obtain indexes while using Iterator
We can obtain
indexes at any point of time while traversing a list using ListIterator. The
methods nextIndex() and previousIndex() are used for this purpose.
4) We cannot add
element to collection while traversing it using Iterator, it throws
ConcurrentModificationException when you try to do it.
We can add element
at any point of time while traversing a list using ListIterator.
5) We cannot
replace the existing element value when using Iterator.
By using set(E e)
method of ListIterator we can replace the last element returned by next() or
previous() methods.
6) Methods of
Iterator:
hasNext()
next()
remove()
Methods of
ListIterator:
add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)
Map Interface
A Map stores data
in key and value association. Both key and values are objects. The key must be
unique but the values can be duplicate. Although Maps are a part of Collection
Framework, they can not actually be called as collections because of some
properties that they posses. However we can obtain a collection-view of maps.
Map Maps unique key to value.
Map.Entry Describe an element in key and value pair in
a map. This is an inner class of map.
NavigableMap Extends SortedMap to handle the retrienal
of entries based on closest match searches
SortedMap Extends Map so that key are maintained in an
ascending order.
TreeMap class
TreeMap class
extends AbstractMap and implements NavigableMap interface.
It creates Map,
stored in a tree structure.
A TreeMap
provides an efficient means of storing key/value pair in efficient order.
It provides
key/value pairs in sorted order and allows rapid retrieval.
LinkedHashMap
class
LinkedHashMap
extends HashMap class.
It maintains a
linked list of entries in map in order in which they are inserted.
EnumMap class
EnumMap extends
AbstractMap and implements Map interface.
It is used for
key as enum
Comparator
Interface
In Java,
Comparator interface is used to order the object in your own way. It gives you
ability to decide how element are stored within sorted collection and map.
Comparator
Interface defines compare() method. This method compare two object and return 0
if two object are equal. It returns a positive value if object1 is greater than
object2. Otherwise a negative value is return. The method can throw a
ClassCastException if the type of object are not compatible for comparison.
Example
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator
class
This class
defines the comparison logic for Student class based on their roll. Student
object will be sotred in ascending order of their roll.
class
MyComparator implements Comparator
{
public int compare(Student s1,Student s2)
{
if(s1.roll == s2.roll) return 0;
else if(s1.roll > s2.roll) return 1;
else return -1;
}
}
public class Test
{
public static void main(String[] args)
{
TreeSet< Student> ts = new
TreeSet< Student>(new MyComparator());
ts.add(new Student(45,
"Rahul"));
ts.add(new Student(11,
"Adam"));
ts.add(new Student(19,
"Alex"));
System.out.println(ts);
}
}
Output :
[ 11 Adam, 19
Alex, 45 Rahul ]
As you can see in
the ouput Student object are stored in ascending order of their roll.
Java Enum
Java Enums can be
thought of as classes that have fixed set of constants.
It can be used
for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum
constants are static and final implicitly. It is available from JDK 1.5.
Points to
remember for Java Enum
enum improves
type safety
enum can be
easily used in switch
enum can be
traversed
enum can have fields,
constructors and methods
enum may
implement many interfaces but cannot extend any class because it internally
extends Enum class
Simple example of
java enum
class
EnumExample1{
public enum
Season { WINTER, SPRING, SUMMER, FALL }
public static
void main(String[] args) {
for (Season s :
Season.values())
System.out.println(s);
}}
Test it Now
Output:WINTER
SPRING
SUMMER
FALL
What is the
difference between Iterator and Enumeration?
1) Iterator can traverse legacy and non-legacy
elements.
Enumeration can
traverse only legacy elements.
2) Iterator is fail-fast.
Enumeration is
not fail-fast.
3) Iterator is slower than Enumeration.
Enumeration is
faster than Iterator.
What is the
difference between List and Set?
List can contain
duplicate elements whereas Set contains only unique elements.
What is the
difference between Set and Map?
Set contains
values only whereas Map contains key and values both.
Why we override
equals() method?
The equals method
is used to check whether two objects are same or not. It needs to be overridden
if we want to check the objects based on property.
For example,
Employee is a class that has 3 data members: id, name and salary. But, we want
to check the equality of employee object on the basis of salary. Then, we need
to override the equals() method.
What is Generics
in Java?
Before generics,
we can store any type of objects in collection i.e. non-generic. Now generics,
forces the java programmer to store specific type of objects.
Advantage of Java
Generics
There are mainly
3 advantages of generics. They are as follows:
1) Type-safety : We can hold only a single type
of objects in generics. It doesn’t allow to store other objects.
2) Type casting is not required: There is no
need to typecast the object.
Before Generics,
we need to type cast.
List list = new
ArrayList();
list.add("hello");
String s =
(String) list.get(0);//typecasting
After Generics,
we don't need to typecast the object.
List<String>
list = new ArrayList<String>();
list.add("hello");
String s =
list.get(0);
3) Compile-Time Checking: It is checked at
compile time so problem will not occur at runtime. The good programming
strategy says it is far better to handle the problem at compile time than
runtime.
List<String>
list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile
Time Error
What if there is
no Generics?
In the following
program, the "Room" class defines a member object. We can pass any
object to it, such as String, Integer, etc.
class Room {
private Object object;
public void add(Object object) {
this.object = object;
}
public Object get() {
return object;
}
}
public class Main
{
public static void main(String[] args) {
Room room = new Room();
room.add(60);
//room.add("60"); //this
will cause a run-time error
Integer i = (Integer)room.get();
System.out.println(i);
}
}
The program runs
totally fine when we add an integer and cast it. But if a user accidentally add
a string "60" to it, compiler does not know it is a problem. When the
program is run, it will get a ClassCastException.
Exception in
thread "main" java.lang.ClassCastException: java.lang.String cannot
be cast to java.lang.Integer
at collection.Main.main(Main.java:21)
You may wonder
why not just declare the field type to be Integer instead of Object. If so,
then the room is not so much useful because it can only store one type of
thing.
When generics is
used
If generic type
is used, the program becomes the following.
class
Room<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class Main
{
public static void main(String[] args) {
Room<Integer> room = new
Room<Integer>();
room.add(60);
Integer i = room.get();
System.out.println(i);
}
}
Now if someone
adds room.add("60"), a compile-time error will be shown like the
following:
We can easily see
how this works. In addition, there is no need to cast the result any more from
room.get() since compile knows get() will return an Integer.
Summary
To sum up, the
reasons to use Generics are as follows:
Stronger type
checking at compile time.
Elimination of
explicit cast.
Enabling better
code reusability such as implementation of generic algorithms
Type Parameters in
Generics
The type
parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like generic
class, we can create generic method that can accept any type of argument.
Let’s see a
simple example of java generic method to print array elements. We are using
here E to denote the element.
public class
TestGenerics4{
public static < E > void
printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40,
50 };
Character[] charArray = { 'J', 'A',
'V', 'A', 'T','P','O','I','N','T' };
System.out.println( "Printing
Integer Array" );
printArray( intArray );
System.out.println( "Printing
Character Array" );
printArray( charArray );
}
}
Output:
Printing Integer
Array
10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T
Wildcard in Java
Generics
The ? (question
mark) symbol represents wildcard element. It means any type. If we write <?
extends Number>, it means any child class of Number e.g. Integer, Float,
double etc. Now we can call the method of Number class through any child class
object.
Let's understand
it by the example given below:
import
java.util.*;
abstract class
Shape{
abstract void
draw();
}
class Rectangle
extends Shape{
void
draw(){System.out.println("drawing rectangle");}
}
class Circle
extends Shape{
void
draw(){System.out.println("drawing circle");}
}
class
GenericTest{
//creating a
method that accepts only child class of Shape
public static
void drawShapes(List<? extends Shape> lists){
for(Shape s:lists){
s.draw();//calling
method of Shape class by child class instance
}
}
public static
void main(String args[]){
List<Rectangle>
list1=new ArrayList<Rectangle>();
list1.add(new
Rectangle());
List<Circle>
list2=new ArrayList<Circle>();
list2.add(new
Circle());
list2.add(new
Circle());
drawShapes(list1);
drawShapes(list2);
}}
Output:
drawing rectangle
drawing circle
drawing circle
What is the
difference between Enumeration and Iterator?
Only major
difference between Enumeration and iterator is 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 by using
Iterator we can manipulate the objects like adding and removing the objects
from collection e.g. Arraylist.
Also Iterator is
more secure and safe as compared to Enumeration because it does not allow other
thread to modify the collection object while some thread is iterating over it
and throws ConcurrentModificationException.
How is Hashmap in
Java implemented internally? What are the pros and cons to use it? What are the
complexities it provides for insert, delete and lookup?
There are four
things we should know about before going into internals of how HashMap works -
HashMap works on
the principal of hashing.
Map.Entry
interface - This interface gives a map entry (key-value pair). HashMap in Java
stores both key and value object, in bucket, as Entry object which implements
this nested interface Map.Entry.
hashCode()
-HashMap provides put(key, value) for storing and get(key) method forretrieving
Values from HashMap. When put() method is used to store (Key, Value) pair,
HashMap implementation calls hashcode on Key object to calculate a hash that is
used to find a bucket where Entry object will be stored. When get() method is
used to retrieve value, again key object is used to calculate a hash which is
used then to find a bucket where that particular key is stored.
equals() -
equals() method is used to compare objects for equality. In case of HashMap key
object is used for comparison, also using equals() method Map knows how to
handle hashing collision (hashing collision means more than one key having the
same hash value, thus assigned to the same bucket. In that case objects are
stored in a linked list.
Where hashCode
method helps in finding the bucket where that key is stored, equals method
helps in finding the right key as there may be more than one key-value pair
stored in a single bucket.
HashMap changes
in Java 8
Though HashMap
implementation provides constant time performance O(1) for get() and put()
method but that is in the ideal case when the Hash function distributes the
objects evenly among the buckets.
But the
performance may worsen in the case hashCode() used is not proper and there are
lots of hash collisions. As we know now that in case of hash collision entry
objects are stored as a node in a linked-list and equals() method is used to
compare keys. That comparison to find the correct key with in a linked-list is
a linear operation so in a worst case scenario the complexity becomes O(n).
To address this
issue in Java 8 hash elements use balanced trees instead of linked lists after
a certain threshold is reached. Which means HashMap starts with storing Entry
objects in linked list but after the number of items in a hash becomes larger
than a certain threshold, the hash will change from using a linked list to a
balanced tree, this will improve the worst case performance from O(n) to O(log
n).
Why Java take 2
byte of memory for store character ?
Java support more
than 18 international languages so java take 2 byte for characters, because for
18 international language 1 byte of memory is not sufficient for storing all
characters and symbols present in 18 languages. Java supports Unicode but c
support ascii code. In ascii code only English language are present, so for
storing all English latter and symbols 1 byte is sufficient.
What is java and
javac ?
.Java tool are
used for run the java program and javac tool are used for compile the java
program.
Why Boolean data
types take zero byte of memory ?
Boolean data type
takes zero bytes of main memory space because Boolean data type of java
implemented by Sun Micro System with a concept of flip - flop. A flip - flop is
a general purpose register which stores one bit of information (one true and
zero false).
Which access
specifier are called universal access specifier ?
Public
Which access specifier is not a keyword ?
Which access specifier is not a keyword ?
Default
Which access specifier is package level access specifier ?
Which access specifier is package level access specifier ?
Default
Type Casting
Assigning a value
of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type
casting is classified into two types,
Widening
Casting(Implicit)
Narrowing
Casting(Explicitly done)
Widening or
Automatic type converion
Automatic Type casting
take place when,
è
the two
types are compatible
è
the
target type is larger than the source type
Narrowing or
Explicit type conversion
When you are
assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
What is the
difference between Method and Constructor
·
Method
can be any user defined name
Constructor
must be class name
·
Method
should have return type
Constructor
should not have any return type (even void)
·
Method
should be called explicitly either with object reference or class reference.
Constructor
will be called automatically whenever object is created
·
Method
is not provided by compiler in any case.
The
java compiler provides a default constructor if we do not have any constructor.
Important points
For Exception Handling:
1. If you do not explicitly use the try catch
blocks in your program, java will provide a default exception handler, which
will print the exception details on the terminal, whenever exception occurs.
2. Super class Throwable overrides toString()
function, to display error message in form of string.
3. While using multiple catch block, always
make sure that exception subclasses comes before any of their super classes.
Else you will get compile time error.
4. In nested try catch, the inner try block,
uses its own catch block as well as catch block of the outer try, if required.
5. Only the object of Throwable class or its
subclasses can be thrown.
Is Iterator a Class?
Iterator is an interface. It is not a class. It is used to iterate through each and every element in a list.
Iterator is implemented Iterator design pattern.


No comments:
Post a Comment