Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, May 9, 2014

Comparator and Comparable in Java

Comparator: Comparator is an interface which is defined in java.util package which means Comparator should be used as a utility to sort objects. Comparator interface in Java has method public int compare (Object o1, Object o2) which is used to compare two different objects.
Let’s see below example.
Student.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

 class Student {
           
            private int marks;
private String name;
            /**
             * @return the marks
             */
            public int getMarks() {
                        return marks;
            }

            /**
             * @return the name
             */
            public String getName() {
                        return name;
            }

            public Student(int marks, String name){
                        this.marks = marks;
                        this.name = name;
                       
            }
            /**
             * @param args
             */
            public static void main(String[] args) {
                        List<Student> studentList = new ArrayList<Student>();
                        studentList.add(new Student(50, "A"));
                        studentList.add(new Student(40, "B"));
                        studentList.add(new Student(60, "C"));
                        studentList.add(new Student(20, "D"));
                        studentList.add(new Student(30, "E"));
                       
                        StudentSortByMarks studentSortByMarks = new StudentSortByMarks();
                        Collections.sort(studentList,studentSortByMarks );
                        for(Student st : studentList) {
                        System.out.println(st.getMarks() + " :::: " + st.getName());
                        }
                        }
            }
           

Let’s create an interface StudentSortByMarks

StudentSortByMarks.java

import java.util.Comparator;
public class StudentSortByMarks implements Comparator<Student> {
            public int compare(Student st1, Student st2) {
                        return st1.getMarks() - st2.getMarks();
                        }          
}
Output:
20 :::: D
30 :::: E
40 :::: B
50 :::: A
60 :::: C
In the above example we have create a class Student. Two instance variables marks and name are declared and values are assigned through a constructor. Two getter methods are declared with which Student marks and name are retrieved later.
The Comparator is implemented by StudentSortByMarks where we are comparing marks of students with method int compare (Student st1, Student st2)
After that when we are running the main () method and After the studentList is sorted, the elements are printed with enhanced for loop and above output is getting generated.

Comparable: Comparable interface in Java is defined in java.lang package. Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. Comparable interface has method public int compareTo (Object o)
Let’s see below example.
Student.java: The Student class implements Comparable interface. Here, Comparable is designed to be generics; that is, Comparable object compares only Student objects.
Two instance variables marks and name are declared and values are assigned through a constructor. Two getter methods are declared with which Student marks and name are retrieved later.
class Student implements Comparable<Student> {

       private int marks;
       private String name;
       /**
        * @return the marks
        */
       public int getMarks() {
              return marks;
       }
       /**
        * @return the name
        */
       public String getName() {
              return name;
       }
        public Student(int marks, String name) {
               this.marks = marks;
               this.name = name;
               }
        
        public int compareTo(Student st1) {
               return this.marks - st1.marks;
               }
        }

StudentSortByMarks.java
Another class StudentSortByMarks is created which creates some Student objects and adds them to ArrayList studentList. The ArrayList object studentList is passed to sort() method of Collections class. The sort() method sorts as per the Comparable interface compareTo() method as Student class implements Comparable interface.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentSortByMarks {
                         public static void main(String args[]) {
                                     List<Student> studentList = new ArrayList<Student>();
                                     studentList.add(new Student(50, "A"));
                                     studentList.add(new Student(40, "B"));
                                     studentList.add(new Student(60, "C"));
                                     studentList.add(new Student(20, "D"));
                                     studentList.add(new Student(30, "E"));
                                     Collections.sort(studentList);
                                     for(Student st : studentList) {
                                                 System.out.println(st.getMarks() + " : " + st.getName());
                                                 }
                                     }
                         }
Output:
20 : D
30 : E
40 : B
50 : A
60 : C

Difference between Comparator and Comparable in Java

Parameter
Comparator
Comparable
Definition
Comparator in Java is defined in java.util package which means Comparator should be used as an utility to sort objects
java.util.Comparator
Comparable interface is defined in java.lang package, which should be provided by default
java.lang.Comparable
Sorting logic
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id, name etc.
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting Strategy
if you want to sort on some other attribute of object then use Comparator
if you want to sort objects based on natural order then use Comparable
Implementation
Class whose objects to be sorted do not need to implement this interface. Some other class can implement this interface.
Ex. StudentSortByMarks class can implement Comparator interface to sort collection of students object by marks
Class whose objects to be sorted must implement this interface.
 Ex. StudentSortByMarks  class needs to implement comparable to collection of students object by marks
Sorting method
int compare(Object o1,Object o2)
This method compares o1 and o2 objects  and returns a integer. Its value has following meaning.
1.positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
int compareTo(Object o1)
This method compares this object with o1 object and returns a integer. Its value has following meaning
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1
Calling method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method

Monday, March 17, 2014

Difference between Hashtable and HashMap in java

HashMap
HashMap implements Map interface which maps key to value. It is not synchronized and is not thread safe. Duplicate keys are not allowed and null keys as well as value are allowed.

HashMap<Interger,String> empHashmap=new HashMap<Integer,String>();
empHashmap.put(1,"Kameshwar");
empHashmap.put(2,null);  // This will work fine

Hashtable

Hashtable implements Map interface which maps key to value. It is synchronized and thread safe. Duplicate keys are not allowed and null key is also not allowed.

Hashtable<Interger,String> empHashmap=new Hashtable<Integer,String>();
empHashmap.put(1,"Kameshwar");
empHashmap.put(2,null);  //not allowed and will throw NullPointer exception at run time

Hashtable vs HashMap:

Parameter
HashTable
HashMap
Synchronized
Yes
No
ThreadSafe
Yes
No
Performance
Due to theadSafe and Synchronized, it is often slower than HashMap
In single threaded environment, it is much faster than Hashtable. So if you do not work in multi thread environment ,then HashMap is recommended
Null key
Do not allow
Allows null key as well as values
Fail fast
enumeration in Hashtable is not fail fast
Iterator in HashMap is fail fast
Extends
It extends Dictionary class which is quite old
It extends AbstractMap class
Alternative
No alternative
You can use ConcurrentHashMap for multi thread environment

Some important points need to be discussed. 

  • Synchonized meaning only one thread can modify one table  at one point of time. When any thread perform update operation on hashtable then it acquires lock on it and other threads have to wait for lock to be released.
  • Fail-fast iterator means if one thread is iterating over HashMap and other thread trying to modify HashMap structurally it will throw ConcurrentModification Exception and fail immediately. Structurally modification means inserting or deleting elements that can change structure of map.

Can we synchronize HashMap?

Yes, We can synchonized a HashMap also with the help of Collections.synchonizedMap(hashmap) so HashMap can be synchronized by using below code.

Map map=Collections.synchonizedMap(hashmap)

Monday, January 13, 2014

Generics In Java


1.      Generics
a)  Generics in Java is one of important feature added in Java 5 along with Enum, autoboxing and varargs , to provide compile time type-safety.
b)     Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at runtime which was quite frequent error in Java code,
c)      Generics allows Java programmer to write more robust and type-safe code.
d)     generics expand your ability to reuse code and let you do so safely and easily.

2.      Non Generics Class using Object
a)      This makes NonGen able to store any type of object, as can the generic version
b)     Its not good because following  two reason .
               i.     explicit casts must be employed to retrieve the stored data
        ii.   many kinds of type mismatch errors cannot be found until run time.

3.      The General Form of a Generic Class
a)      syntax for declaring a generic class:
i.  class class-name<type-param-list> { // ...
b)     syntax for declaring a reference to a generic class
i.                    class-name<type-arg-list> var-name =new class-name<type-arg-list>(cons-arg-list);

4.      bounded types
a)      When specifying a type parameter, you can create an upper bound that declares the
       superclass from which all type arguments must be derived.
b)     This is accomplished through the use of an extends clause
c)      In addition to using a class type as a bound, you can also use an interface type.
 In fact,
d)     you can specify multiple interfaces as bounds.
e)      bound can include both a class type and one or more interfaces. In this case, the class type must be specified first.
f)       class Gen<T extends MyClass & MyInterface> { // ...
g)     Here, T is bounded by a class called MyClass and an interface called MyInterface. Thus,any type argument passed to T must be a subclass of MyClass and implement MyInterface.
h)     Syntax
i.  I <T extends superclass>
ii.  This specifies that T can only be replaced by superclass, or subclasses of superclass.

5.      Using Wildcard Arguments

a)      The wildcard argument is specified by the ?, and it represents an unknown type.
b)     One last point: It is important to understand that the wildcard does not affect what type of Stats objects can be created. This is governed by the extends clause in the Stats declaration. The wildcard simply matches any valid Stats object.

6.      Bounded Wildcards (Ex. Generic7)
a)      In general, to establish an upper bound for a wildcard, use the following type of wildcard
b)     expression:<? extends superclass>
c)      where superclass is the name of the class that serves as the upper bound
d)     You can also specify a lower bound for a wildcard by adding a super clause to a wildcard
e)      declaration. Here is its general form:<? super subclass>
f)       In this case, only classes that are superclasses of subclass are acceptable arguments. This is an exclusive clause, because it will not match the class specified by subclass.

7.      Creating a Generic Method(Ex Generic8)
a)       it is possible to create a generic method that is enclosed within a non-generic class.
b)     generic methods can be either static or non-static. There is no restriction in this regard.
c)      Generalized syntax
<type-param-list> ret-type meth-name(param-list) { // ...

8.      Generic Constructors (Ex Generic9)
a)      It is also possible for constructors to be generic, even if their class is not.

9.      Generic Interfaces
a)      you can also have generic interfaces
b)     In general, a generic interface is declared in the same way as is a generic class.
c)      In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface. For example,the following attempt to declare MyClass is in error:
d)     class MyClass implements MinMax<T> { // Wrong!{ // OK
e)      Because MyClass does not declare a type parameter, there is no way to pass one to MinMax.
f)       In this case, the identifier T is simply unknown, and the compiler reports an error. Of course,if a class implements a specific type of generic interface, such as shown here:
g)     class MyClass implements MinMax<Integer> { // OKthen the implementing class does not need to be generic.
h)     Benefit of Generic Interface
i.  it allows you to put constraints (that is, bounds) on the types of data for which the interface can be implemented.
ii.     It can be implemented for different types of data.

i)       Syntax:
i.     interface interface-name<type-param-list> { //
ii.  Here, type-param-list is a comma-separated list of type parameters. When a generic interface is implemented, you must specify the type arguments, as shown here:
iii.                     class class-name<type-param-list> implements interface-name<type-arg-list> {

10.  Raw Types and Legacy Codes
a)      Because support for generics is a recent addition to Java, it was necessary to provide some transition path from old, pre-generics code. At the time of this writing, there are still millionsand millions of lines of pre-generics legacy code that must remain both functional and compatible with generics. Pre-generics code must be able to work with generics, and generic code must be able to work with pre-generic code.
b)     To handle the transition to generics, Java allows a generic class to be used without any type arguments. This creates a raw type for the class. This raw type is compatible with legacy code, which has no knowledge of generics. The main drawback to using the raw type is that the type safety of generics is lost.
c)      A raw type is not type safe. Thus, a variable of a raw type can be assigned a reference to any type of Gen object. The reverse is also allowed;
d)     Generic Class Hierarchies

11.  Rules of Genrics
a)      Parametrized type like Set<T> is subtype of raw type Set and you can assign Set<T> to Set, following code is legal in Java:

Set setOfRawType = new HashSet<String>();
setOfRawType = new HashSet<Integer>();

b)     Gen<int> strOb = new Gen<int>(53); // Error, can't use primitive type