PUB ID

Monday, 30 November 2015

Difference between hashset and treeset and linkedhashset in java

TreeSet, LinkedHashSet and HashSet all are implementation of Set interface. there are some differences exist between them.



HashSet
LinkedHashSet
TreeSet
How they work internally?
HashSet uses HashMap internally to store it’s elements.
LinkedHashSet uses  LinkedHashMap internally to store it’s elements.
TreeSet uses TreeMap internally to store it’s elements.
Order Of Elements
HashSet doesn’t maintain any order of elements.
LinkedHashSet maintains insertion order of elements. i.e elements are placed as they are inserted.
TreeSet orders the elements according to supplied Comparator. If no comparator is supplied, elements will be placed in their natural ascending order.
Performance
HashSet gives better performance than the LinkedHashSet and TreeSet.
The performance of LinkedHashSetis between HashSet and TreeSet. It’s performance is almost similar to HashSet. But slightly in the slower side as it also maintains LinkedList internally to maintain the insertion order of elements.

TreeSet gives less performance than the HashSet and LinkedHashSet as it has to sort the elements after each insertion and removal operations.
Insertion, Removal And Retrieval Operation
HashSetgives  performance of order O(1) for insertion, removal and retrieval operations.

LinkedHashSet also gives performance of order O(1) for insertion, removal and retrieval operations.
TreeSet gives performance of order O(log(n)) for insertion, removal and retrieval operations
Null elements
HashSet allows maximum one null element.
LinkedHashSet also allows maximum one null element.
TreeSet doesn’t allow even a single null element. If you try to insert null element into TreeSet, it throws NullPointerException.
Memory Occupation
HashSet requires less memory than LinkedHashSet and TreeSet as it uses only HashMap internally to store its elements.
LinkedHashSet requires more memory than HashSet as it also maintains LinkedList along with HashMap to store its elements.
TreeSet also requires more memory than HashSet as it also maintains Comparator to sort the elements along with the TreeMap.
When To Use?
Use HashSet if you don’t want to maintain any order of elements.
Use LinkedHashSet if you want to maintain insertion order of elements.
.
Use TreeSet if you want to sort the elements according to some Comparator


 
HashSet Example
 
HashSet<Dog> dset = new HashSet<Dog>();
dset.add(new Dog(2));
dset.add(new Dog(1));
dset.add(new Dog(3));
dset.add(new Dog(5));
dset.add(new Dog(4));
Iterator<Dog> iterator = dset.iterator();
while (iterator.hasNext()) {
 System.out.print(iterator.next() + " ");
}
 
Output:
5 3 2 1 4
 
LinkedHashSet Example

LinkedHashSet<Dog> dset = new LinkedHashSet<Dog>();
dset.add(new Dog(2));
dset.add(new Dog(1));
dset.add(new Dog(3));
dset.add(new Dog(5));
dset.add(new Dog(4));
Iterator<Dog> iterator = dset.iterator();
while (iterator.hasNext()) {
 System.out.print(iterator.next() + " ");
}
 
The order of the output is certain and it is the insertion order:
2 1 3 5 4
 
 TreeSet Example

TreeSet<Integer> tree = new TreeSet<Integer>();
tree.add(12);
tree.add(63);
tree.add(34);
tree.add(45);
 
Iterator<Integer> iterator = tree.iterator();
System.out.print("Tree set data: ");
while (iterator.hasNext()) {
    System.out.print(iterator.next() + " ");
}

Output is sorted as follows:
Tree set data: 12 34 45 63 


Wednesday, 25 November 2015

what is Upcasting and Downcasting in Java

UpCasting
     The Process of Storing subclass object reference into superclass reference variable is called upcasting.

For Example
        Parent p=new Child(); // upcasting

DownCasting 
             downcasting is explicitly type conversion
  The process  of retrieving the subclass object reference from superclass reference variable ,and storing it into same subclass referenced variable is called downcasting.

For Example
        Parent p=new Child(); // upcasting
        Child c=(Child)p; // downcasting
For performing downcasting The Source type must have IS-A relationship with Destination type

Example Programe
interface A
{
  void display();
}
class B implements A
{
    public void display() {
        System.out.println("Am in class B");
    }
 
}
class C extends B
{
    @Override
    public void display() {
        System.out.println("Am in class C");
    }
}
- See more at: http://www.codemiles.com/java/difference-between-upcasting-and-downcasting-t7627.html#sthash.wIkUQTlE.dpuf

 interface A
{
  void display();
}
class B implements A
{
    public void display() {
        System.out.println("Am in class B");
    }

}
class C extends B
{
    @Override
    public void display() {
        System.out.println("Am in class C");
    }
}


interface A
{
  void display();
}
class B implements A
{
    public void display() {
        System.out.println("Am in class B");
    }
 
}
class C extends B
{
    @Override
    public void display() {
        System.out.println("Am in class C");
    }
}
- See more at: http://www.codemiles.com/java/difference-between-upcasting-and-downcasting-t7627.html#sthash.wIkUQTlE.dpuf
 Applying upcasting

public static void main(String[] args) {

        // Upcasting from subclass to super class.
        A aRef=new C();

        aRef.display();//Am in class C
      }


Applying Downcasting

public static void main(String[] args) {

        // Upcasting from subclass to super class.
        A aRef=new C();

        aRef.display();//Am in class C
        //Downcasting of reference to subclass reference.
        B bRef=(B) aRef;
        bRef.display();//Am in class C

    } 








interface A
{
  void display();
}
class B implements A
{
    public void display() {
        System.out.println("Am in class B");
    }
 
}
class C extends B
{
    @Override
    public void display() {
        System.out.println("Am in class C");
    }
}
- See more at: http://www.codemiles.com/java/difference-between-upcasting-and-downcasting-t7627.html#sthash.wIkUQTlE.dpuf
interface A
{
  void display();
}
class B implements A
{
    public void display() {
        System.out.println("Am in class B");
    }
 
}
class C extends B
{
    @Override
    public void display() {
        System.out.println("Am in class C");
    }
}
- See more at: http://www.codemiles.com/java/difference-between-upcasting-and-downcasting-t7627.html#sthash.wIkUQTlE.dpuf

Tuesday, 24 November 2015

Difference between Collection and Collections in java

Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

Collection Interface :

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections Class:

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.

Collections.max() This method returns maximum element in the specified collection.
Collections.min() This method returns minimum element in the given collection.
Collections.sort() This method sorts the specified collection.
Collections.shuffle() This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection() This method returns synchronized collection backed by the specified collection.
Collections.binarySearch() This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint() This method returns true if two specified collections have no elements in common.
Collections.copy() This method copies all elements from one collection to another collection.
Collections.reverse() This method reverses the order of elements in the specified collection.

Monday, 23 November 2015

Difference between String,StringBuffer and StringBuilder in java

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  String Constant Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .

demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder


StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe . 


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area |  String Constant Pool           Heap                       Heap
Modifiable     |  No (immutable)             Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                             Yes                          No
 Performance |         Fast                          Very slow                  Fast
----------------------------------------------------------------------------------