Thursday, April 24, 2014

JAVA 8

EARLIER:
Collections.sort(inventory, new Comparator() {
    public int compare(Apple a1, Apple a2){
       return a1.getWeight().compareTo(a2.getWeight());
    }
});

JAVA 8:
inventory.sort(comparing(Apple::getWeight));

EARLIER:
File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
    public boolean accept(File file) {
        return file.isHidden();
    }
});

JAVA 8:
File[] hiddenFiles = new File(".").listFiles(File::isHidden);

Tuesday, July 26, 2011

Is this a Design issue or Eclipse's issue or Java's loophole

Let us have the following classes defined in eclipse's work space:

public abstract class A {
public void foo() {
System.out.println("Hi.. this is foo()");
}
}

public interface I {
void foo();
}

public class B extends A implements I {
public void bark() {
System.out.println("Hi.. this is bark()");
}
}

public class C {
public void woo() {
I i = new B();
i.foo();
}
}

Now the problem is eclipse doesn't show any references for A.foo() on searching through
References -> Project or
References - Hierarchy

I see this a design issue. What do you think? Please post your comment on this.

Friday, December 31, 2010

Java: What to do for known unchecked exceptions

Take a look at the javadoc for java.util.Collection#add

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html#add(E)

There's a whole slew of unchecked exceptions mentioned:

Throws:
UnsupportedOperationException - add is not supported by this collection.
ClassCastException - class of the specified element prevents it from being added to this collection.
NullPointerException - if the specified element is null and this collection does not support null elements.
IllegalArgumentException - some aspect of this element prevents it from being added to this collection.

It is recommend thoroughly documenting the possible exceptions thrown by your methods this way. In a way, it's even more important to do this for unchecked exceptions, as checked exceptions are somewhat self-documenting (the compiler forces the calling code to acknowledge them).