Thursday, January 17, 2013

java.util.Arrays.ArrayList

We are not discussing about the ArrayList class which is there in java.util package.

The ArrayList class that comes under java.util.Arrays is a private static nested class inside Arrays class.
This class implements List interface and extends AbstractList class.

It doesnot provide implementation for all the methods of List Interface. Infact it provides implementation to very few methods.

Methods in Arrays$ArrayList:-

public boolean contains(Object object)
public E get(int location)
public int indexOf(Object object)
public int lastIndexOf(Object object)
public E set(int location, E object)
public int size()
public Object[] toArray()

So if we will try access any other methods of List using runtime polymorphism it will access the method in AbstractList class. Hence throw an Exception if it is thrown in the AbstractList class.

Ex:- If we try to access add(Object obj) or remove(int location) it will throw UnsupportedOperationException.

Lets consider below scenario

List<String> list = Arrays.asList("tom","pom","kom","bom");
Iterator<String> i = list.iterator();
while(i.hasNext())
{
if(i.next().equals("pom"));
i.remove();//Exception thrown at this line
}


The above code will compile successfully but exception will be thrown at runtime when we will try to invoke remove();

Reason:- When we invoke remove() Iterator tries to invoke the remove(int location) of ArrayList class which is there in Arrays class. Since ArrayList class of Arrays class does not provide implementation for remove(int location) method it invokes remove(int location) of AbstractList class. Hence throws an UnsupportedOperationException.






Iterator and Iterable

Coming soon....

Saturday, January 5, 2013

Collection in Java

Collection is a data structure which provides us a way to store a group of Objects in a single variable.


Collection in Java is nothing but an API that has been provided by JRE in rt.jar under java.util package. This API makes the operations like searching, sorting, addition, delete easier for us.

In Collection we have two major Interfaces
1)Collection
2)Map

Lot many implementing classes and Interfaces are there in collection framework but we will discuss few commonly used ones.
Below provided is a very small portion of Collection and Map hierarchy which is used in daily life very frequently.










The basic difference between a List and a Map is List contains a group of Objects where Map contains Kay and value pair.

Ex:-

Without Generics

List li = new ArrayList();
Map map = new HashMap();
With Generics

List<Object> li = new ArrayList<Object>();
Map<Object,Object> map = new HashMap<Object,Object>();

Collection Interface hierarchy

Two very commonly used data structure under Collection hierarchy are List and Set. Both List and Set are Interfaces.
The basic difference between a List and Set is, List can contain duplicate element but Set cannot.

Frequently used concrete classes that Implement List

ArrayList :- This is the best preferred when we want to access elements form List very frequently. This is not synchronized. We will get the data in same order in which these were inserted to the ArrayList. We can add null value to ArrayList.

Syntax:- 
List<Object> li = new ArrayList<Object>();

LinkedList:- This is also one concrete class which implements List Interface. Doing operations like adding deleting is faster in LinkedList. We can add null value to LinkedList. Takes more memory that ArrayList.
Specialty of LinkedList is adding an element at a particular index in the list is much faster than the ArrayList.
It maintains ordering.i.e.We will get the data in same order in which these were inserted

Syntax:-
List<Object> li = new LinkedList<Object>();


Vector:- This is also another concrete  class which implements List.  This roughly equivalent to ArrayList . We can add null value to Vector. It maintains ordering.
The only difference is Vector is synchronized where as ArrayList is not synchronized.

Syntax:- 
List<Object> li = new Vector<Object>();

Q) When to use LinkedList , ArrayList and Vector?

Ans:- If you need to do operations like add, remove frequently or add an element at a particular index in the List you should go for in LinkedList.

If you are simply accessing the the elements from the List its better to use ArrayList.

Vector is most useful is a Thread safe application.

Frequently used concrete classes that Implement Set

HashSet:- This a concrete class that implements Set Interface. We can not add duplicate elements to it. We can add null value to HashSet. It does NOT maintain ordering. i.e. We may not get the data in same order in which these were inserted

LinkedHashSet:- This is a concrete class that implements Set Interface and extends HashSet. This is the combination of HashSet and LinkedList. We can add null value to LinkedHashSet.


TreeSet:- This is a concrete class which implements NavigableSet Interface which comes under Set hierarchy. So TreeSet also implements Set Interface. Specialiy of Tree set is, its naturally ordered. Irrespective of the order in which elements will be added but we will get the elements in sorted order.
We can NOT add null values to it.

Map Interface hierarchy

Map contains Key value pair where key is unique. 

Q)What will happen if we will add a pair with an existing key.
Ans:- The existing value will be overridden with the new value.

Frequently used concrete classes that Implement Map


Hashtable:- This Implements Map interface. This is synchronized, hence most useful in Thread safe application. We can NOT add null for key or value.

HashMap:- This is the most used concrete class that implements Map Interface.  This is very similar to Hashtable except this is not Synchronized and we can add null for key or value.

LinkedHashMap:- This Implements Map interface and extends HashMap. This is a combnination of LinkedList and HashMap. We can add null for key or value.

TreeMap:- It implements NavigableMap Interface and NavigableMap Interface comes under Map hierarchy. Hence TreeMap implements Map Interface. Irrespective of the sequence we will add the key value pairs, those will be sorted in ascending order for Keys.
We can NOT add null for key or value.

Use of Iterator in Java

To know about Iterator please visit Iterator and Iterable.

Iterator can be used to traverse through a Collection.

Ex:-



List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");

Iterator<String> i = list.iterator();
String str = "bob";
String local;
while(i.hasNext())//Returns true if the iteration has more elements.
{
local = i.next(); // Returns the next element in the iteration
System.out.println(local);
if(str.equals(local))
{
i.remove();//Removes from the underlying collection the last element returned by the iterator
}
}



Note:- In above example if we use 
List<String> list = Arrays.asList("tom", "jon","bob","james"); at first line it will throw an exception UnsupportedOperationException when we call remove() of Iteretor. For more information please visit ArrayList in Arrays class.



Q:- What if I call remove() first before calling next(); ?

Ans:- I will throw IllegalStateException if we call remove() before calling next();.

for each loop in Collection

This is a new feature of Java that was introduced in Java 1.5. It is used to traverse thorough a Collection or an Array.

Ex with List:-

List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");
Iterator<String> i = list.iterator();

for(String local:list)
{
System.out.println(local);
}




Q & A

Q)Are all the methods in Vector class are synchronized?
Ans:-No. Few are synchronized and few are not.
Ex:- add(int index, E element)- NotSYnchronized but add(E e) is synchronized.
remove(Object o) is not synchronized but remove(int index) is synchronized.

Q) How can I sort a List ?
Ans:- There are two ways to sort a list.
1)Use TreeSet. Accordiong to the property of TreeSet the values will be inserted to the list in the sorted order.
2)By using the static method sort(List<T> list) Collections class.

List<Test> li =new LinkedList<Test>();
Collections.sort(li);
Note:- Element of the List should Implement Comparable Interface. Here Test class should Implement Comparable Interface.

Q) Can I add a Object to a List<String> . i.e.List of String 

Ans:-
Whenever this kind question comes we should keep one thing in mind i.e. Java does not do downcasting automatically but it does upcasting. We have to do downcasting mannually.So when we add an Object to List<String> it throws compilation error. Because it tries to cast Object to String. Since downcasting in java is not a default property it will not let us add an Object to List<String>. But if we will add a String to List<Object> it will compile successfully.

List<String> list = new ArrayList<String>();
list.add(new Object());// Compilation error thrown at this line
Compilation error is thrown at 2nd line in above code.

List<Object> list = new ArrayList<Object>();
list.add(new String());

The above code compliles successfully.




Thursday, January 3, 2013

Constructor in java

Constructor  in Java

Constructor in java is like a method  which is used to create instance of a class. In simple words Constructor constructs object. 
It provides the simplest way to create object with new keyword.
Constructor is declared with the same name as its class name.

Types:-

1)parameterized Constructor :- Constructor with arguments
2)Default Constructor :- Constructor without arguments

Ex:- 


public class Test 
{
public int count;

private Test(int count)                    //parameterized Constructor
{
       this.count = count;
}
public Test()                                 //Default Constructor
{

}
}



->constructor can not be inherited.

->Interface cannot have constructor


Why Interface cannot have constructor ?

Ans:- Interface cannot be instantiated.i.e. we cannot create an object of Interface.

Note:- But a Abstract class can have constructor.

Reason:- constructor is used to initialized member variables. We can have member variables in Abstract class which can be initialized in constructor.
Though we can have member variables in Interface those are static and final by default. Which can not be initialized in constructor and has to be initialized during the time of declaration.

Member variables in Interface could have been initialized in static initilizer block, but we can NOT have static initilizer block in Interface. So we have to initialize it during the time of declaration. 
Hence we don't need a constructor in Interface.

Q)Here the question arises is we cannot create an Instance of a Abstract class. Then how to call the constructor of it.

Ans:- The constructor of abstract class can be called from the constructor of implementing class using super keyword. Example of super has been given below.


->A constructor cannot be abstract, static, final, native, strictfp, or synchronized. 
   
Note:-Only access specifiers are allowed for constructor are public, protected & private

Why constructor cannot be abstract?

Ans:- When we declare a method abstract i.e. the method cannot have body. But we use constructor to create objects and initialize instance variables which contradicts with the property of abstract keyword.

Why constructor cannot be static?

Ans:- We use static keyword when we want to declare a class variable or method at class level which will be invoked by using Class name not by using objects.
Though syntax of a constructor is like a method it is not a member of a class (unlike instance variable, class variables or methods ). constructor can not be accessed using Object or Class itself. So it makes no sense to declare a constructor static.

Why constructor cannot be inherited?


Ans:- Only methods and instance variables can be inherited in Java. Since constructor is neither of them we can not inherit it. In order to use super class constructor we use "super" keyword.

Ex:-
public class Test extends TestParent
{
Test()
{
super();
}
}



Why constructor cannot be final?

Ans:- When we declare a method as final it can not be inherited  Anyways we cannot inherit constructor. So there is no point making a constructor final

Why constructor cannot be synchronized?

Ans:- synchronized keyword is used in multithreaded application for shared resources. When we make any method or block synchronized only one thread can access it at a time. If we would make a constructor synchronized then the object will be created one after another in queue which will not help us anyway rather it hinders the performance.


-> Constructor cannot have return type. If we will try to return something from a constructor it will consider it as a method and will through a warning. 
Though it will not throw a compile time error, it will throw a warning to change it to constructor.

Ex-



Ex:-

public class Test
{
public int count;

private Test() {
}

public void Test(int count) {
this.count = count;
System.out.println("count is " + this.count);
}

public static void main(String[] args) {
Test test1 = new Test();
test1.Test(5);
}
}





The above program will compile successfully with a warning.
Output:- count is 5

->Java provides us default constructor but if we will declare a parameterized constructor then we have to explicitly write the default constructor to access it otherwise it will throw a compilation error.

Ex:-

public class Test 
{
public static void main(String[] args) {
Test test1 = new Test();
}
}



The above code will compile successfully. But if we will add a parameterized constructor it will throw a compile time error.

Ex:-
public class Test
{
Test(int i) {}

public static void main(String[] args) {
Test test1 = new Test(); // Compilation error will be thrown at this
// line
}
}




Ex:-














How to call a constructor from another?
Ans:-
A constructor can be called from another constructor by using "this" or "super" keyword. But this will be the first line inside the constructor.

public class Test
{

Test() 
        {
this(3);
}

Test(int i) {
}
}

Can we call constructor using this and super from a single constructor ?
Ans:- NO, Since constructor call using this and super from a constructor will always be the first line, either of one can be used but not both.

->If no constructor is declared in the class compiler creates a default constructor during the time of compilation.

->By default constructor returns the instance of the class. But we cannot do that explicitly.

-> constructor can be overloaded as in the first example we have used both parameterized as well as default constructor 

private Constructor 

-> We can use private access specifier to make a constructor private. If we make a constructor private the same cannot be accesses from out side the class.

use:- 
When we don't want to create an object of the class out side the class. Used in singleton Design pattern