Some days ago, my friend vic told me about one unknown java feature, that recalls some kind of enclosure. He show to me that in java you can execute something like this:
HashMap myMap = new HashMap(){{put(new Integer(1),"one");
put(new Integer(2),"two");
put(new Integer(3),"three");
put(new Integer(4),"four");
}};
Then myMap is a new already initialized HashMap, so for example if you want to build a Map factory with some List filled with beans you can do something like this
class Book{
public Integer isbn;
public String title;
public String author;
...
// here goes setters and getters
}
In Java 5.
// ordered books by isbn;
public Map
buildCatalog(final List <book> books){return new TreeMap(){{
}for(Book book: books){
}};put(book.getIsbn(), book);
}
In Java 4 this will look like:
// ordered books by isbn;
public Map
buildCatalog(final List books){ return new TreeMap(){{
for(int i=0; i<books.size;i++){
book=(Book)books.get(i);
put(book.getIsbn(), book);
}
}};
This code creates an anonimous class, that inherits TreeMap, then internally calls the method put, but differs to the clasic implementation of an anonimous class, for example when you write an ActionListener as an anonimous class you write it to define the ActionPerform method but you don't call it at the moment.
I consider this interesting, I couldn't find some official explanation of this feature, but I will continue searching. Comment's are welcome :)
Friday, February 29, 2008
Unknown Java Feature
Subscribe to:
Posts (Atom)

