Thursday, 27 February 2014

Comparator vs Comparable

To those of you who do not about Comparable and Comparator these are interfaces provided to sort objects of a given class.

Comparator vs Comparable in Java


Here are some of the common differences,

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package, which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified. I have shared lot of tips on how to override compareTo() method and avoid some common mistakes programmer makes while implementing Comparable interface.

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java  can be used as keys in a SortedMap like TreeMap or elements in a SortedSet for example TreeSet, without specifying any Comparator.

So which one we should use?



That depends on the problem you are dealing with.If you have a class whose instances store information about employee.And if you want to sort these objects on the basis of employee id than Comparable would be enough but  if we look at other side of this problem you might ask that hey can't we sort them with salary or any other basis and also provide user with the option so that he can provide the sort parameter.This is where Comparator comes into picture .With Comparator implemented on a class user can pass parameter saying okay now i want to sort these objects by salary or retirement year.


Example using Comparator

import java.util.*;
public class sort{
static ArrayList<DvdInfo> list=new ArrayList<DvdInfo>();
sort()
{
DvdInfo a=new DvdInfo("Batman Begins "," Christian Bale");
DvdInfo b=new DvdInfo("The Dark Knight "," Aaron Eckhart");
list.add(a);
list.add(b);
}
public static void main(String[] args)
{
sort dummy=new sort();
title t=new title();
Collections.sort(list,t);
System.out.println(list.toString());
actor a=new actor();
Collections.sort(list,a);
System.out.println(list.toString());
}
}
class DvdInfo{
private String title;
private String actor;
DvdInfo(String a,String b)
{
title=a;
actor=b;

}
String getTitle()
{
return title;
}
String getActor()
{
return actor;
}
public String toString(){
return title+""+actor;
}
}
class title implements Comparator<DvdInfo>{
public int compare(DvdInfo a,DvdInfo b)
{
return a.getTitle().compareTo(b.getTitle());
}
}
class actor implements Comparator<DvdInfo>{
public int compare(DvdInfo a,DvdInfo b)
{
return a.getActor().compareTo(b.getActor());
}
}

Output is

[Batman Begins  Christian Bale, The Dark Knight  Aaron Eckhart]
[The Dark Knight  Aaron Eckhart, Batman Begins  Christian Bale]



Example using Comparable

import java.util.*; 
public class sam{ 
public static void main(String[] args) 

Test a=new Test();    //Object a
Test b=new Test();   //Object b
a.c=-50;                 //Assigning variable c of object a to -50
b.c=55; //Assigning variable c of object b to 55

int x=b.compareTo(a);   //Comparing a and b 
System.out.println(""+x); 


class Test implements Comparable{ 
Integer c; 
public int compareTo(Object t) 

Integer v=10; 
return c.compareTo(v);   //this is a test condition

}
Output will be 

1



Wednesday, 26 February 2014

.hashCode() :Introduction


The hashcode was introduced in java for comparison of the objects in java.
To compare two or more objects using the .equals() method their hash code must be same.
Yeah it's true in our previous blog we discussed about the differences between == and .equals().
The one step ahead this concept will give you a sneak peek into the background working of .equals().
So what exactly is hashcode ?
Hash Codes are used in data sorting.In data sorting we assign a hash code to every object if two objects have same hash code they are put together in same tuple.
Consider this example ,
We are using a simple hash code algorithm.
Note: This is not a real hashcode algorithm it is just an example as real hashcode algorithms are way tougher.
Suppose we want to store names Alex,May and Amy.


So, hashcode


ALEX=1+12+5+24= 42


MAY=13+1+25= 39


AMY=1+13+25= 39
So the names having same hash codes are put together in same tuple.
So May and Amy are in same tuple but Alex will be in another tuple.
So,when you search about May it will calculate it's hash code which is 37 so it will start searching in the tuple which is marked 37.
It is also true that you can override the hash code and equals of any class.
But remember to maintain the consistency of the program the overriding must be such that it follows our basic rule i.e two objects are equal if their hash code id equal.
These are some of the basics of hash codes they have a large application in data sorting in Array Lists etc.

Comparing two objects of a class using compareTo()


To compare to objects we use object1.compareTo(object2)
Let's see how it works with the statement below.

int x=b.compareTo(a); //Comparing a and b


The value x will show the result of comparison.

Value of x                                              Assertion from value of x
x>0                                                                       b>a
x<0                                                                       b<a
x=0                                                                       b==a


You can make your own conditions for comparing two objects by overriding .compareTo()
i.e implementing java.util.Comparable .


For comparing two objects of same class you must use interface Comparable available in java.util.*;


So let's consider a basic example.


import java.util.*;
public class sam{
public static void main(String[] args)
{
Test a=new Test(); //Object a
Test b=new Test(); //Object b
a.c=-50; //Assigning variable c of object a to -50
b.c=55; //Assigning variable c of object b to 55



int x=b.compareTo(a); //Comparing a and b
System.out.println(""+x);
}
}
class Test implements Comparable{
Integer c;
public int compareTo(Object t)
{
Integer v=10;
return c.compareTo(v); //this is a test condition
}
}


Output will be
1



Explanation of code:
We have created a public class sam in it's main method we created two instances of Test class which are a and b. Now we assign the variable c of object a to -50 and variable c of object b to 55.
Now int x=b.compareTo(a); will show the comparision value.
In class Test we implement Comparable and override compareTo(), and return the result .The Integer v is a dummy to compare the object .You can use instead of v your instance variables such as price,id no etc.


Tuesday, 25 February 2014

The Python self variable trouble !




Hi there fellas. In this post I am going to teach you about the self variable in python. I have seen many beginners struggling to grasp the concept of self variable. If you are one of them then this post is for you. So lets start by making a class involving the self variable.


class Restaurant(object):
bankrupt = False
def open_branch(self):
if not self.bankrupt:
print("branch opened")
x = Restaurant()
x.bankrupt
Restaurant().bankrupt



>>> x = Restaurant()
>>> x.bankrupt
False

>>> y = Restaurant()
>>> y.bankrupt = True
>>> y.bankrupt
True

>>> x.bankrupt
False

class Restaurant(object):
bankrupt = False
def open_branch(this):
if not this.bankrupt:
print("branch opened")


A simple class :So here is our class:

First let me explain the above code without the technicalities. First of all we make a class Restaurant. Then we assign it a property “bankrupt” which is currently false. After that we assign it a function open_branch which can only occur if “bankrupt” is False which means that the Restaurant has some money.

Making a resturant:

Now that we have made a class for a Restaurant, lets actually make a resturant:

Now x is a Restaurant which has a property bankrupt and a function open_branch. Now we can access the property bankrupt by typing:

The above command is same as:

Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the Restaurant class to x whereas in the second case it referred to Restaurant(). Now if we have another Restaurant y, self will know to access the bankrupt value of y and not x. For example check this example:

The first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.

Free Tip:

However self is not a reserved keyword in python it’s just a strong convention. Many people say that why do we have to write self ? Why can’t we have it set automatically like in Java ? Someone also filed a PEP (improvement suggestion) in which he suggested to remove the explicit assignment of self keyword. However Guido Van Rossum (the maker of python) wrote a blogpost in which he told why explicit self has to stay.

The .equals() and == confusion

==(comparison operator)

Every thing is a class or an object in java .Thus == is used normally to compare two values of primitive type such as int,float etc. ,But in the case of String or Wrapper classes it checks that whether two objects have same memory address or not.

Blown by it! But stay with me as this article will clear your basics about object comparison.

What == does is that it checks memory addresses in case of objects.

Let's judge it with an example.

Integer i1 = 1000;

Integer i2 = 1000;

if(i1 != i2) System.out.println("different objects");

Produces the output:

different objects


As i1 and i2 are different objects thus the output is desired.

Wait this get's more weird!

Integer i3 = 10;

Integer i4 = i3;

if(i3 == i4) System.out.println("same object");


This example produces the output:

same object


Yikes!What happened with == and != ? Why is != telling us that i1 and i2 are different objects, when == is saying that i3 and i4 are the same object? In order to save memory, whenever in java if we assign one object to another ,the object is not copied but both objects share same memory reference.

Note: When == is used to compare a primitive to a wrapper, the wrapper will be

unwrapped and the comparison will be primitive to primitive.


Such as

Integer a=10;

int b=10;

System.out.println(a==b); //a is first unboxed to its primitive value and then comparison took place


Output is

true

.equals() It checks whether the two objects are meaningfully same i.e if two wrappers are taken into consideration they are equal if they are of same type and have same primitive value.

Example

Integer i1 = 1000;

Integer i2 = 1000;

if(i1.equals( i2)) System.out.println("meaningfully same");


Output will be

meaningfully same

Why we use .equals() for string comparison?

As you know String is a class if use == that will compare memory addresses of String objects.

Consider the following example:

public class t{

public static void main(String[] args)

{

String x="Tilak";

String y="Tilak";

if(x==y)System.out.print("same");

}

}


Output: same


You must be wondering as,I said that == compares memory addresses but in this String example it works fine.But try to understand the mechanism behind it.

The topic which we need to understand to clear this concept is String Pool.


String Pool

To save memory java has so called String Pool which contains all the declared Strings .When two or more String objects have same value they refer or point to the same String value stored in pool.



So the above example worked not because “Tilak”==”Tilak” but it worked because a single copy of “Tilak” is present in the pool and both x and y point to this single copy.


Thus using .equals() ensures that values are compared not their memory addresses.


To know more about .equals(),Please read about .hashCode().


Monday, 24 February 2014

The Basic Java Terminology Confusion

I have often seen people confusing between basic java technologies such as JDK,JRE,JAVAFX etc.
I am trying to sort this problem out by explaining this matter in a very simple manner.


ABOUT JDK AND JRE                       


JRE: Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.


JDK: It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs.
Usually, when you only care about running Java programs on your browser or computer you will only install JRE. It's all you need. On the other hand, if you are planning to do some Java programming, you will also need JDK.


So                             JDK=JRE+development tools
                             JRE=just virtual machine to run apps



ABOUT JAVA-SE ME FX AND EE

JavaSE = Standard Edition. 

This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...).


JavaEE = Enterprise Edition.

 From wikipedia: "The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server." In other words, if your application demands a very large scale, distributed system, then you should consider using JavaEE. Built on top of JavaSE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JMS), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, JavaServer Pages, etc...


JavaME = Micro Edition.

This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. JavaME provides a subset of the functionality of JavaSE, but also introduces libraries specific to mobile devices. Because JavaME is based on an earlier version of JavaSE, some of the new language features introduced in Java 1.5 (eg. generics) are not available.


JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.



Difference between Java Applets and Servlets


Applets are downloaded to client system and executed.
Whereas servlets are executed from servers.



Note (also) that until very recently, Java SE was known as J2SE, and Java EE was known as J2EE. The situation is confused further by the fact that many people (especially recruiters) confuse J2EE with EJBs (which are only one of the technologies in Java EE).



Tips to new java users:


If you are new to Java, definitely start with JavaSE.
I would also recommend using Eclipse or NetBeans instead of Komodo IDE, since this is the most widely used editor within the industry. Because it has built in support for Java, you will benefit from all the usual advantages of using an IDE: code assist, syntax highlighting, auto compile, etc...

You can find Netbeans+JDK bundle in this link
https://netbeans.org/downloads/

To begin learning java ,I would recommend the following links:-
http://docs.oracle.com/javase/tutorial/index.html

If you want to prepare for OCJP refer this book but first match the contents with the latest syllabus.
This book is also beneficial for java learners.

SCJP Sun Certified Programmer for Java 6 Exam 310-065 By Katherine Sierra and Bert Bates

Download link below
https://java.net/downloads/jfjug/SCJP%20Sun%20Certified%20Programmer%20for%20Java%206-0071591060.pdf




Good luck!

If you have any doubts regarding java you can always comment your problems.