Wednesday, August 12, 2009

method overloading in java (with umberto tozzi)

Method overloading allows you to use the same method name with different arguments. As long as the "different arguments" constraint holds, you are free to change the return type, the access modifier and the thrown exception of the method. Lets see it on an example.


private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

public void sings(int times){
System.out.println("Tozzi sings "+times+" times");
}



I'm free to change the access modifier private to public of the overloaded method as long as I use another argument type in the method.



private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

String sings(int times){
String message = "Tozzi sings "+times+" times";
System.out.println(message);
return message;
}


Above I change the access modifier (from private to package access) and the return type (from none to String).


private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

private void sings(boolean isUmbertoSick) throws Exception{
if(isUmbertoSick)
throw new Exception("Umberto Tozzi is sick");

System.out.println("Tozzi sings 'Ti amo'");
}


Above I added an exception to the overloaded method. The method checks if Umberto Tozzi is sick and throws an exception in this case. If he's ok, Umberto gladly sings his hit single "Ti Amo".

An interesting case is when you overload methods which have two classes with superclass, subclass relationship between (one class inherits the other) as argument. Lets see it in an example.


class Song { }
class Ballad extends Song { }

public class UmbertoTozzi {

private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

private void sings(Song song){
System.out.println("Tozzi sings the song "+song);
}

private void sings(Ballad ballad){
System.out.println("Tozzi sings the ballad "+ballad);
}

public static void main(String[] args) {
// create UmbertoTozzi object
UmbertoTozzi tozzi = new UmbertoTozzi();
// create a Ballad and Song object
Ballad ballad = new Ballad();
Song song = new Song();
// give the ballad and song references to
// the sings method
tozzi.sings(ballad); /* output: Tozzi sings the ballad Ballad@a6aeed */
tozzi.sings(song); /* output: Tozzi sings the song Song@126804e */

// bind a Ballad object
//to a Song reference
Song newSong = new Ballad();

tozzi.sings(newSong);
/* output: Tozzi sings the song Ballad@b1b4c3 */
}
}


There are three overloaded methods above. One accepts arguments of type String, the other Song and the last one Ballad. Notice that Ballad extends Song which means that Ballad is a Song. Ballad is the subclass while Song is the superclass. The last output is quite confusing. I sent a Ballad object to the sings method. Why sings(Song song) is called instead of sings(Ballad ballad) ? The answer is quite plain. The object related to the reference is not checked. If we put it in another way, the method call is done in compile time, not in runtime. So the compiler sees that the reference type is Song and it calls the corresponding method.
Long live Umberto Tozzi!

Tuesday, August 11, 2009

Saturday, August 8, 2009

how to sort using comparators

Although Collections class' sort method is quite handy, there will be times you'll need to do tricky stuff while sorting. But you can still use this static method with your Comparator that'll ensure the desired sorting behavior.

Lets quote the definition of Comparator class:
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order


Assume that we want to sort a List of floats by considering only the part after the dot. So we will consider 63 of 3.63 and 72 of 2.72 and their increasing order will be {3.63, 2.72} because 63 < 72. The code of the Comparator is below.


// we use generics (Float here) for avoiding a downcast
class FloatComparator implements Comparator < Float >{

public int compare(Float f1, Float f2) {
// for instance, 323.432 - 323 ~= 0.432
Float f1_ = f1 - f1.intValue(); /* intValue() returns the floor integer (not the closest integer) */
Float f2_ = f2 - f2.intValue();
/* after stripping the float from the integer part we use float's compareTo function compare the remaining part of the number */
return f1_.compareTo(f2_);
}


}




We implemented the Comparator interface in the class. In public int compare method we first remove the integer part of the float and then compare the rest. If you must do more trickier stuff you have to consider few things. I'm quoting from Sun's Comparator documentation:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that
sgn(compare(x, z))==sgn(compare(y, z)) for all z.



As we use the compareTo method of Float, we don't have to think about the above cases. They are already handled.

Lets see our FloatComparator in action.


public class SortingWithComparator {

public static void main(String[] args) {
List < Float > numberList = new ArrayList < Float > ();
numberList.add(323.432F);
numberList.add(34.234F);
numberList.add(-81.01F);
numberList.add(49.736F);

for(Float number : numberList)
System.out.println(number);

Collections.sort(numberList, new FloatComparator()); /* sort numberList using the FloatComparator */
System.out.println("------- after sorting takes place -----");

for(Float number : numberList)
System.out.println(number);

}
}


The output is:


323.432
34.234
-81.01
49.736
------- after sorting takes place -----
-81.01
34.234
323.432
49.736

Friday, August 7, 2009

eclipse magic part 1: automatically generate getters and setters for your instance variables

Everyone who tried to write a getter / setter (accessor, mutator) method for more than 2-3 fields knows that it's a pain. Eclipse can automatically generate a getter/setter method for the instance variable you choose. Assume that I have a java bean for a student (StudentBean).


public class StudentBean {
private int studentId;
private String name;
private float gpa;
}


If I'm going to write a get/set method for each variable I'll have to write 6 methods in total. Let Eclipse to this job.
 Source > Generate Getters and Setters


Then choose the fields.



You can choose the insertion point of the automatically generated methods, their order and their access modifiers. My new StudentBean is now like this:


public class StudentBean {

private int studentId;
private String name;
private float gpa;

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public float getGpa() {
return gpa;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setGpa(float gpa) {
this.gpa = gpa;
}

}

Wednesday, August 5, 2009

burpee the ultimate workout!

Pretty confident title right? This exercise develops lots of different muscles and does not take too much time. I've been doing burpee for few months and I can't recommend it enough. Take a look at the video below for doing it right.