Sabtu, 31 Mei 2014

Difference between TreeSet, LinkedHashSet and HashSet in Java with Example




TreeSet, LinkedHashSet and HashSet all are
implementation of
Set interface and by virtue of that, they follows contract of Set interface i.e. they do not allow duplicate elements.
Despite being from same type hierarchy,  there are lot of difference between them;
which is important to understand, so that you can choose most appropriate Set implementation based upon
your requirement. By the way difference between
TreeSet and HashSet or LinkedHashSet is also
one of the popular Java Collection interview
question
, not as popular as Hashtable vs HashMap or ArrayList vs Vector
but still
appears in various Java interviews. In this article we will see difference between
HashSet, TreeSet and LinkedHashSet on various points e.g. Ordering of elements,
performance, allowing null etc and then we will see When to use
TreeSet or LinkedHashSet or simply HashSet
in Java
.




Difference between TreeSet, LinkedHashSet
and HashSet in Java



TreeSet vs HashSet vs LinkedHashSet in Java with ExampleTreeSet, LinkedHashSet and HashSet in Java
are three Set implementation in collection framework and like many others they
are also used to store objects. Main feature of
TreeSet is
sorting, 
LinkedHashSet is
insertion order and
HashSet is just general purpose
collection for storing object. HashSet is implemented using HashMap in Java while TreeSet
is implemented using
TreeMap
TreeSet is a SortedSet
implementation which allows it to keep elements in the sorted order defined by
either Comparable or Comparator interface.
Comparable is used for natural order sorting and Comparator for custom order sorting of
objects, which can be provided while creating instance of
TreeSet. Anyway before seeing
difference between
TreeSet, LinkedHashSet and HashSet, let's see
some similarities between them:





1) Duplicates : All three implements Set interface means they are
not allowed to store duplicates.




2) Thread safety : HashSet, TreeSet and LinkedHashSet are not thread-safe, if you use them
in multi-threading environment where at least one Thread  modifies Set you need to externally synchronize them.





3) Fail-Fast Iterator : Iterator returned by TreeSet, LinkedHashSet and HashSet are fail-fast Iterator. i.e. If
Iterator is modified after its creation by any way other than Iterators
remove() method, it
will throw
ConcurrentModificationException with best
of effort. read more about fail-fast vs fail-safe Iterator
he
re




Now let’s see difference between HashSet, LinkedHashSet and TreeSet in
Java
:





Performance and Speed
: First difference between them comes in terms of  speed. 
HashSet is
fastest,
LinkedHashSet is second on performance or
almost similar to
HashSet but TreeSet is bit
slower because of sorting operation it needs to perform on each insertion.
TreeSet provides
guaranteed
O(log(n)) time for common operations like
add, remove and contains, while
HashSet and LinkedHashSet offer
constant time performance e.g. O(1) for add, contains and remove given hash
function uniformly distribute elements in bucket.





Ordering : HashSet does not
maintain any order while
LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains
sorting order or elements.





Internal
Implementation :
HashSet is backed by an HashMap
instance,
LinkedHashSet is implemented using HashSet and
LinkedList while
TreeSet is backed up by NavigableMap in Java
and by default it uses TreeMap.





null : Both HashSet and LinkedHashSet allows
null but
TreeSet doesn't allow null but TreeSet doesn't allow
null and throw java.lang.NullPointerException
when you will insert null into
TreeSet. Since TreeSet uses compareTo() method of
respective elements to compare them 
which throws
NullPointerException while comparing with null,
here is an example:





TreeSet cities


Exception in thread "main" java.lang.NullPointerException


        at
java.lang.String.compareTo(String.java:1167)


        at
java.lang.String.compareTo(String.java:92)


        at
java.util.TreeMap.put(TreeMap.java:545)


        at
java.util.TreeSet.add(TreeSet.java:238)





Comparison : HashSet and LinkedHashSet uses equals() method in Java for comparison but TreeSet uses compareTo() method for
maintaining ordering. That's why
compareTo()
should be
consistent to equals in Java. failing to do so break general contact of Set
interface i.e. it can permit duplicates.





TreeSet vs HashSet vs LinkedHashSet - Example



Let’s compare all these Set implementation on some points by writing Java
program. In this example we are demonstrating difference in ordering, time
taking while inserting 1M records among TreeSet,
HashSet and LinkedHashSet in Java.
This will help to solidify some points which discussed in earlier section and
help to decide when to use
HashSet, LinkedHashSet or TreeSet in Java.





import java.util.Arrays;

import java.util.HashSet;

import java.util.LinkedHashSet;

import java.util.Set;

import java.util.TreeSet;



/**

 * Java program to demonstrate difference between TreeSet, HashSet and LinkedHashSet


 * in Java Collection.

 * @author

 */


public class SetComparision
{

 

   
public static void main(String args[]){            

        HashSet
<String> fruitsStore = new HashSet<String>();

        LinkedHashSet
<String> fruitMarket = new LinkedHashSet<String>();

        TreeSet
<String> fruitBuzz = new TreeSet<String>();

     

       
for(String fruit: Arrays.asList("mango", "apple", "banana")){

            fruitsStore.
add(fruit);

            fruitMarket.
add(fruit);

            fruitBuzz.
add(fruit);

       
}

       


       
//no ordering in HashSet – elements stored in random order

        System.
out.println("Ordering in HashSet :" + fruitsStore);





        //insertion
order or elements – LinkedHashSet storeds elements as insertion


        System.
err.println("Order of element in LinkedHashSet
:"
+ fruitMarket);





       
//should be sorted order – TreeSet stores element in sorted
order


        System.
out.println("Order of objects in TreeSet
:"
+ fruitBuzz); 


     





       
//Performance test to insert 10M elements in HashSet, LinkedHashSet
and TreeSet


        Set
<Integer> numbers = new HashSet<Integer>();

       
long startTime = System.nanoTime();

       
for(int i =0; i<10000000; i++){

            numbers.
add(i);

       
}




       
long endTime = System.nanoTime();

        System.
out.println("Total time to insert 10M
elements in HashSet in sec : "


                            + (endTime - startTime));

     

     

       
// LinkedHashSet performance
Test – inserting 10M objects


       
numbers =
new LinkedHashSet<Integer>();

        startTime = System.
nanoTime();

       
for(int i =0; i<10000000; i++){

            numbers.
add(i);

       
}

        endTime = System.
nanoTime();

        System.
out.println("Total time to insert 10M
elements in LinkedHashSet in sec : "


                            + (endTime -
startTime
));

       


       
// TreeSet performance Test – inserting 10M objects

        numbers =
new TreeSet<Integer>();

        startTime = System.
nanoTime();

       
for(int i =0; i<10000000; i++){

            numbers.
add(i);

       
}

        endTime = System.
nanoTime();

        System.
out.println("Total time to insert 10M
elements in TreeSet in sec : "


                            + (endTime -
startTime
));

   
}

}



Output

Ordering in HashSet :
[banana, apple, mango]

Order of element in LinkedHashSet
:[mango, apple, banana]

Order
of objects in TreeSet :
[apple, banana, mango]

Total time to insert 10M elements in HashSet in sec :
3564570637

Total time to insert 10M elements in LinkedHashSet in sec :
3511277551

Total time to insert 10M elements in TreeSet in sec :
10968043705











When
to use
HashSet, TreeSet and LinkedHashSet in Java


Since all three implements Set interface they can be used for
common Set operations like not allowing duplicates but since
HashSet, TreeSet and LinkedHashSet has there
special feature which makes them appropriate in certain scenario. Because of sorting
order provided by
TreeSet, use TreeSet when you
need a collection where elements are sorted without duplicates. HashSet are rather general purpose
Set implementation, Use it as default
Set
implementation if you need a fast, duplicate free collection.
LinkedHashSet is
extension of
HashSet and its more suitable where you
need to maintain insertion order of elements, similar to List without compromising
performance for costly
TreeSet. Another use of LinkedHashSet is for
creating copies of existing Set, Since
LinkedHashSet preservers
insertion order, it returns Set which contains same elements in same order like
exact copy. In short,  although all three
are
Set interface implementation they offer distinctive feature, HashSet is a
general purpose Set while
LinkedHashSet provides insertion order
guarantee and
TreeSet is a SortedSet which stores
elements in sorted order specified by Comparator or Comparable in Java.








How to
copy object from one Set to other


Here is code example of LinkedHashSet which
demonstrate How
LinkedHashSet can be used to copy objects from one
Set to another without losing order. You will get exact replica of source Set, in terms
of contents and order. Here static method
copy(Set source) is written
using Generics, This kind of parameterized method pr
ovides
type-safety and help
to avoid
ClassCastException at runtime.





import java.util.Arrays;

import java.util.HashSet;

import java.util.LinkedHashSet;

import java.util.Set;



/**

 * Java program to copy object from one HashSet to another using LinkedHashSet.

 * LinkedHashSet preserves order of element while copying elements.

 *

 * @author Javin

 */


public class
SetUtils{

   

    public static void
main(String args[]) {

       

        HashSet<String> source = new
HashSet<String>(Arrays.asList("Set, List, Map"));

        System.out.println("source : " + source);

        Set<String> copy = SetUtils.copy(source);

        System.out.println("copy of HashSet using LinkedHashSet: " +
copy);

    }

   

    /*

     * Static utility method to copy Set in Java

     */


    public static <T> Set<T> copy(Set<T>
source){

           return
new LinkedHashSet<T>(source);

    }

}

Output:

source : [Set, List, Map]

copy of HashSet using LinkedHashSet: [Set,
List, Map]








Always code for interface than implementation so that you can replace HashSet to LinkedHashSet or TreeSet when your
requirement changes. That’s all on difference
between
HashSet, LinkedHashSet and TreeSet in Java.  If you know
any other significant difference between
TreeSet, LinkedHashSet and HashSet which is
worth remembering than please add as comment.





Other tutorials from Java Collection Framework






























Source:http://javarevisited.blogspot.com/2012/11/difference-between-treeset-hashset-vs-linkedhashset-java.html

Got some t-shirts



I just got some post from Germany.






That's a nice surprise!






It's from Markus Eisele, who also ever interviewed me.






That's no problem! It's a pretty nice GlassFish t-shirt!






This is the back side.





There was also another shirt inside, an Oracle Open World t-shirt.





Thank you, Markus! :)



Source:http://balusc.blogspot.com/2012/11/got-some-t-shirts.html

Difference between final, finally and finalize method in Java






What is difference between final, finally and finalize method is
asked to my friend in a Java
interview
with one of the US based Investment bank. Though it was just a
telephonic round interview, he was asked couple of good questions e.g. how
to avoid deadlock in Java
, How
get() method of HashMap works
and one of the puzzle which is based on
recursion. In short
final keyword can be used along with variable,
method and class and has different meaning for all of them.
finally is another
Java keyword which is used in Exception handling along with
try, catch, throw
and throws
.
finalize() is a special method in Java which
is called by Garbage
Collector
before reclaiming GC eligible objects. In this Java interview
questions article we will compare final
vs finally vs finalize
and highlight some important difference between
final, finally and finalize method in
Java.





final vs finally vs finalize in Java



Difference between final vs finally vs finalize in JavaAs I said earlier final keyword can be used along with variable,
method and Class
in Java
. If you make a variable
final, you can
not change it's value, it will act like a
constant. final variables
are initialized at the time of creation except in case of blank final variable which is initialized in Constructor. If you make a method
final in Java, you can not override
it in sub class . If you make a class
final means it
can not be sub classed. Making a class final automatically makes all its method
final and this is sometime required due to security reason, This is one of the
reason Why
String is final in Java
. In short final is not related at all with either
finally or finalize keyword. final
keyword also help to write Immutable classes which are critical for designing
thread-safe multi-threading system and reducing amount of synchronization. I
would suggest to see What
is final in Java
for more information about
final keyword.





Now let's see What is finally in Java? As I said finally is used
for exception handling along with
try and catch. As per
Java programming language’s rule, for exception handling you at least need
either
catch or finally block. finally block has
special advantage over catch that its guaranteed to be executed despite
whether Exception is thrown or not, this makes it, an ideal place to close
system resource e.g. InputStream
or
OutputStream, which is required to release scarce file
descriptor. Closing streams, network connection, database connection in finally
block is good coding practice in Java. By the way from Java 7 you can use try
with resource block
to close resource automatically. Since
finally is
guaranteed to be executed on most cases, it also gives birth to some tricky Java questions where finally doesn't execute e.g. returning value from
finally block, calling
System.exit from try block etc. finally block
always execute, except in case of JVM dies i.e. calling
System.exit() . Again
finally is not related to
final or finalize in any
way.





Now let’s see What is finalize() method, finalize() is called
by Garbage collection thread just before collecting eligible Objects. This is
the last chance for object to perform any cleanup but since its not guaranteed
that whether finalize() will be called, its bad practice to keep resource till
finalize call. Though you can build a safety net on
finalize by double
checking scarce resources. See 10
points on finalize method
to know more about specific points of finalize().





So, final, finally and finalize all are
different keyword, they are used for different purpose. only similarity between
them is that they are a Java programming language keyword, other than that
final, finalize and finally are
completely different than each other.





Other Java programming interview questions from Javarevisited :





























Source:http://javarevisited.blogspot.com/2012/11/difference-between-final-finally-and-finalize-java.html

4 ways to search Java Array to find an element or object - Tutorial Example




Searching in Java Array sounds familiar? should be,  because its one of frequently used operations
in Java programming. Array is an index based data structure which is used to
store elements but unlike Collection classes like ArrayList or HashSet which has
contains() method, array
in Java doesn't have any method to check whether an element is inside array or
not. Java programming language provides several ways to search
any element in Java array
. In this Java tutorial we will see 4 examples of
searching Array in Java for an element or object.  Every example is different than other and some
of them are faster and others are slow but take less memory. These technique
also valid for different types of array e.g. primitive and object array. I
always suggest to prefer
List over Array
until you need every bit of performance from your Java
application, it not only convenient to work but also more extensible.





4 ways to search array in Java



Here are my 4 ways to search Java Array with examples





1) Searching Array by converting Array to ArrayList in Java


How to search Object in a Java array with exampleArrayList in Java has a convenient method called contains() which
returns true if object passed to it are inside ArrayList. by converting
an array into ArrayList in Java
we can easily use this option for searching
any element in Java array.





2) Search Java array by converting Array to HashSet


Just like we can leverage ArrayList's contains
method we can also use
HashSet contains() method which has O(1) response
time for search. So if you need constant search time to find an element in array,
consider converting your Array into HashSet in Java. see the code section for complete
example of searching elements in Java array using HashSet's
contains()
method.





3) Searching Java Array using Arrays.binarySearch()


Binary Search is another faster way of searching elements in Java array but it requires array to be sorted
while earlier examples of finding elements on Array can be used with both sorted
and unsorted array
. java.util.Arrays class provides both sort() and binarySearch() for first
sorting an array and than performing binary search on it.
Arrays.binarySearch() method returns
>=0
if it finds elements in Array. see code section for full code example of
binarySearch in Java array.





4) Finding element in Java array using foreach loop


This is plain, old, brute force way of searching elements on array in Java
or any other programming language like C or C++. You iterate
through array
comparing each elements to input and returning true once you
have matched. this is a completely linear operation and if your array is large
and input is at rear end it can take long time to search array.
O(n) operations
are also not preferred.




One more way of searching an element in array is by using  Apache commons ArrayUtils class. ArrayUtils class provide several overloaded method which accept array and item to be found e.g. int array, long array or Object array and returns true or false if Array contains that element. This requires just one line of code but you need to include Apache commons library in your classpath. See  How to find index of element in Java array for complete code example in Java.


Code Example of Searching Java array to find elements



here is complete code examples of all 4 ways of searching java arrays.
you can use any way as per your need but
HashSet() is best in
terms of speed and consider using that.





import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

import java.util.Set;



public class
SearchTest {



    public static void
main(String args[])
{



        //searching element
on unsorted Java array


        //searching java
array using ArrayList


        List<Integer> array = Arrays.asList(1, 3, 5, 2, 4);

        if (array.contains(3)) {

            System.out.println("Element found
inside Java array using" +


                                 "ArrayList
contains() method"
);

        };



        Set<Integer> arraySet = new
HashSet<Integer>(array);



        if (arraySet.contains(3)) {

            System.out.println("Element found on
Java array using" +


       
                         "HashSet contains method"
);

        };

     

        //searching element
on sorted Java array


        //unsorted String
array


        String[] cities = new
String[]{"Washington",
"London", "Paris",
"NewYork"};

     

        //sorting array in
java


        Arrays.sort(cities);

     

        //searching on
sorted array in java using Arrays binarySearch() method


        if(Arrays.binarySearch(cities, "Paris") >=0 ){

            System.out.println("Element found on
sorted String Java" +


                                  "array
using binary search"
);

        }

     

        //plain old for loop
for searching elements in Java array


        String input = "London";

        for(String city: cities){

            if(city.equals(input)){

               System.out.println("Found elements in
Java array using for loop"
);

            }

        }



    }

}





Output


Element found inside Java
array using  ArrayList contains() method


Element found on Java
array using HashSet contains method


Element found on sorted
String Java array using binary search


Found elements in Java
array using for loop





That’s all on How to search an element inside Array in Java. You can use
any of the above method to search your Java array for any object. Remember that Collection classes like
HashSet and ArrayList use equals()
method
to determine if two objects are equal or not. So if your testing for
custom objects make sure you override equals and hashCode method and follow equals
and hashCode contract in Java
.





Other Java Collection tutorials and examples from Javarevisited






























Source:http://javarevisited.blogspot.com/2012/11/4-ways-to-search-object-in-java-array-example.html