Monday, June 4, 2012

JAVA: Generics

Courtesy : http://java.sun.com/docs/books/tutorial/java/generics

public class Box {

    private T t; // T stands for "Type"          

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

During compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem.

A declaration of Box, for example, would generate an error on the second occurrence of T, but Box, however, would be allowed.

The most commonly used type parameter names are:
  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

Static, when to use

Ever wondered when we see STATIC modifier in code, "what is it?". This article explains when to use it and beauty of it. A MUST go through for all who love to write aesthetic code.

http://www.codeproject.com/Articles/15269/Static-Keyword-Demystified

Summary: Declare methods or variables or properties as static when you think you don't need an object to access the corresponding. Static classes are different in different languages. In C# declaring a class to be static means that it contains only static members. So, recommendation is that write all generic and helper functions in a static class.