Sunday, February 10, 2013

Comparable vs. Comparator

At a first glance, these two interfaces seems to have no difference and it is easy to confuse both.

Comparable interface (java.lang)
This is used by the Collections.sort() and Arrays.sort(), so the elements in the collection needs to implement this interface, in order to be sorted.
This interface is frequently implemented in the API by String, Wrapper Classes, Date, Calendar...
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

CompareTo returns an int with value:
negative    if this object < another object
zero          if this object == another object
positive     if this object > another object


class A implements Comparable<A>{
  String name=new String();

  public String getName(){ return name;}

  @Override
  public int compareTo(A o) {
    return name.compareTo(o.getName());
  }
}

class Test {
  public static void main ( String args[ ] ) {
    List<A> s= new ArrayList<A>();
    s.add(new A());
    s.add(new A());
    Collections.sort(s);  //if the collection does not implement Comparable, it will fail to compile in this line
 }
}


Remember that:
When overriding equals(), the argument is of type Object
When overriding compareTo(), the argument should be of the type you're sorting (but Object is allowed if you don't use Generics).

Comparator interface (java.util)
There an overloaded version of the sort method that takes both a List and something called a Comparator.
Comparator gives you the ability to sort a given collection any number of different ways, so that we can sort instances of any class.

The class that implements Comparator is a separate class from the class whose instances you want to sort, this is used as an argument by the Collections.sort() and Arrays.sort()


class MySort implements Comparator<String>{
  @Override
  public int compare(String one, String two) {
    return one.compareTo(two);
  }
}

class Test {
  public static void main ( String args [ ] ) {
    List<String> s= new ArrayList<String>();
    s.add("one");
    s.add("two");
    Collections.sort(s,new MySort());
  }
}



Searching Arrays and Collections with Comparable/Comparator
Searches are performed with the binarySearch() method.
The collection to be searched has to be sorted first, otherwise the result may become unpredictable (compiles, but the result may not be right).

If the collection was sorted with a natural order (elements implement Comparable), then a Comparator cannot be used to do the search (compiles, but the result may not be right).
E.g
Arrays.sort(array) must be used with
Arrays.binarySearch(array,elementToSearch);


If the collection was sorted with a Comparator, then it must be searched with a Comparator  (compiles, but the result may not be right).
E.g
Arrays.sort(array,someComparatorInstance) must be used with Arrays.binarySearch(array,elementToSearch,someComparatorInstance);

Result:
Successful searches returns an int index of the element being searched.
Unsuccessful searches returns a negative int index of the insertion point, that would be used to keep the collection properly sorted. The result formula for unsuccessful searched is (- (insertion point) -1 ).

Thursday, February 7, 2013

Tools: Process Explorer

Process Explorer is an excellent Microsoft tool that allows to check process dependencies, which DLL processes have been opened or loaded, watch the CPU consumption or just track leaks. Process Explorer provides insights about applications... check it out!




Wednesday, February 6, 2013

SCJP 6 doubts: implicit imports

There are implicit imports that do not need to be declared.
The classes in java.lang package can be used without importing any package, this is an implicit import, so don't be fooled if you see a question that looks like that the import is missing.

What classes can we see in the java.lang package?
JavaSE 6 API just tells us which ones belong to this package: basically its the String, StringBuilder, StringBuffer, Thread, wrappers (Integer, Float,...), Object, System, Runtime, Exception, and a lot of other classes which you can use directly.

The real exam always has line numbers on the left side of the code, so if you see that it does not start with line 1, you don't have to worry about the imports, and assume that the imports (and packages) are right.
If the code starts at line 1, just assume you're looking at the entire file. If you see that the code uses classes that belong to other packages besides java.lang, (e.g class File needs import java.io.*) then you can say for sure that the right answer is "compilation fails" due to missing imports.

Default package
If you have a class within the default package (no package declaration is found), and you create another class that has a relashionship with the first one, then no import is needed (because both are in the default package);

1. public class A{
2. int i=0;
3. }

1. public class B extends A{
2. }

Theme color generator

Kuler is a cool website from Adobe, to generate color themes.
Or you can also try the Color Scheme Designer.

Thursday, January 3, 2013

Java Web Start Cache Viewer is not showing cached applications!

I have a Windows 7 64-bit with Java installed (no matter what version it is) and my Java Web Start Cache Viewer is not showing cached applications!
With this 64-bit Windows 7, when I go to Start -> Settings -> Control Panel -> Java, then click at General tab, "View" button, no cached applications are seen, but I've just downloaded and run a jnlp file just a minute ago.
There is something wrong in here.

So, I googled it, and found the solution that I wish to share with you.

1. Run the cmd window from C:\Windows\SysWOW64
2. Download and run again the jnlp with the command: javaws <url of the jnlp file>
3. Type the command: javaws -viewer

Now the cached application loaded from the jnlp file is displayed correctly in this Java Cache Viewer window and you are able to add a shortcut to it from your desktop. Just right click the cached application and select "Install Shortcuts" from the context menu.

That's it!


Monday, December 17, 2012

Whizlabs SCJP 6.0 Simulator "Error parsing question"

If you get an error message at the Whizlabs SCJP 6.0 Simulator saying "Error parsing question" at the start of an exame, ignore it and take the exame again.

If at the end of the exam, you have a message box that does not allow you to check you score, ignore it and go to the "Performance History". From there, you are able to check your score and review your questions.

Sunday, December 9, 2012

SCJP 6 Questions - Question 63

 class C {  
   public static void main ( String ka [ ] ) {  
     while ( false ) {  
       System.out.println ( "Value" ) ;  
     }  
   }  
 }  

What is the output?
1. compile time error
2. prints Value infinitely
3. Runtime Exception
4. None of the above