Monday, March 15, 2010

Java Generics

  • introduced in J2SE 5.0
  • adds robustness/stability on code by making more bugs detectable at compile time
  • normal way can cause runtime ClassCastException
    public class Box {
        private Object object;
        public void add(Object object) {
            this.object = object;
        }
        public Object get() {
            return object;
        }
    }
        Box integerBox = new Box();
        integerBox.add("10"); // note how the type is now String
        Integer someInteger = (Integer)integerBox.get();

  • sample generic version with type variable T
    public class Box {
    private T t; // T stands for "Type"      
    public void add(T t) {
        this.t = t;
    }
    public T get() {
        return t;
    }
    }
        Box integerBox = new Box();
        integerBox.add(new Integer(10));
        Integer someInteger = integerBox.get(); // no cast!

  • generic method/constructor
    public static <U> void fillBoxes(U u, List<Box<U>> boxes) {
    for (Box<U> box : boxes) {
        box.add(u);
    }
    }
    Crayon red = ...;
    List<Box<Crayon>> crayonBoxes = ...;
    // normal way
    Box.<Crayon>fillBoxes(red, crayonBoxes);
    // with type inference
    Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon

  • Bounded Parameter types -> when variables are restricted to certain types, upper bound only
    <U extends Number & MyInterface> // uses extend for both classes & interfaces
  • Unknown type/wilcard bounds -> represented by wildcard character "?"

    3 different flavors of wildcards:
    • " ? " - the unbounded wildcard. It stands for the family of all types.
    • " ? extends Type " - a wildcard with an upper bound. It stands for the family of all types that are subtypes of Type , type Type being included.
    • " ? super Type " - a wildcard with a lower bound. It stands for the family of all types that are supertypes of Type , type Type being included.
    // Box<Integer> and Box<Double> are not subtypes of Box<Number>
    Box<Number> box = new Box<Integer>(); // compile-time error
    
    // Box<Integer> and Box<Double> are subtypes of Box<? extends Number>
    Box<? extends Number> box = new Box<Integer>(); // ok
    
    Integer i = new Integer(1);
    Number n = i;
    // compile-time error
    // Integer is not '? extends Number'
    // we are not sure that the instance type of Box is Integer, so we cannot add i
    box.add(i); 
    
    // compile-time error
    // Number is not '? extends Number'
    // we are sure that the type of Box extends a Number but we are not sure of the 
    //     instance type of n, so we cannot add n
    // what if runtime type of Box is Box<Double> but n is Integer
    box.add(n)
    
    // compile-time error
    // we are not sure that the type of Box is an Integer
    Integer i2 = box.get();
    
    // we are sure that the type of Box is always extends a Number
    Number n2 = box.get(); // ok
    
    // sample using upperbound & lowerbound wildcards
    public class Collections {
    public static <T> void copy
    ( List<? super T> dest, List<? extends T> src) {  // bounded wildcard parameterized types
       for (int i=0; i<src.size(); i++)
         dest.set(i,src.get(i));
    }
    }

  • Type Erasure -> when generic types are instantiated, all generic information are removed leaving only the raw type. Box becomes Box only.
    public class MyClass {
        public static void myMethod(Object item) {
            if (item instanceof E) {  //Compiler error
                ...
            }
            E item2 = new E();   //Compiler error
            E[] iArray = new E[10]; //Compiler error
            E obj = (E)new Object(); //Unchecked cast warning
        }
    }

Sources:
http://java.sun.com/docs/books/tutorial/java/generics/index.html
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

To Study:

-SSL, certificates, keystore, keytool
-html
-jsp
-jsp el(expression lang)
-extjs
-dwr
-tld (tags)

-j2ee
-java
-servlets

-struts
-spring

-drools

-jdbc
-ibatis
-db2
-sql

-ibml
-properties file (adv. of constants in java file)
-logging, log4j

-servers, tomcat
-deployment (war, jar, ear)
-eclipse
-cvs/clearcase/svn
-maven

TODO:
-check ResourceBundle if there's a properties file

Saturday, March 6, 2010

Java Inheritance

  • Variables

    Kinds of variables base on scope: local, instance, class

    Hiding/Shadowing Variables
    - redeclaring a variable that’s already been declared somewhere else. The closest scope is used when you refer it through simple name.

    1) local var hides instance var
    - use this to access the instance var

    2) instance var hides inherited var
    - use super.name or cast the object to its super class, with the syntax ((Superclass)object).name
    - when the variable is accessed thru the object containing it, the variable used depends on the type the object it was declared with or casted to, not the runtime type of the object.

  • Methods

    Overloading
    - same name, diff arguments, return type doesn't matter

    Overriding
    - same signature (method name + arguments), same return type diff classes
    - instance to instance method only

    Hiding
    - static to static only
    - when the method is called thru the object containing it, the method used depends on the type the object it was declared with or casted to, not the runtime type of the object.

    Not allowed in methods but allowed in variables/fields:
    - static to non-static or vice versa
    - narrowing visibility
    - different return type (but same signature/name) -> compile error in methods

  • Object
    - implicit superclass of all classes
    - must be overridden in objects -> equals(), hashCode(), toString()

    clone() method
    -protected|public Object clone() throws CloneNotSupportedException
    aCloneableObject.clone();
    - aCloneableObject must implemenet Cloneable interface
    - default behavior of Object's clone() -> creates an object of the same class as the original object and initializes the new object's member variables. But if a member variable is an external object, say ObjExternal, ObjExternal is not cloned but shared. A change in ObjExternal made by one object will be visible in its clone also.

    equals() method
    - uses ==
    - if overridden, u must override hashCode() too. If two objects are equal, their hash code must also be equal.
    public boolean equals(Object obj) {
       if (obj instanceof Book)
           return ISBN.equals((Book)obj.getISBN());
       else
           return false;
    }
  • Abstract vs Interface
    - http://mindprod.com/jgloss/interfacevsabstract.html
    - when to use one over the other:
    General rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

Friday, March 5, 2010

Sample CVS config spec

-main
element * CHECKEDOUT
element * /main/LATEST
load \Acctsvcs

-branch
element * CHECKEDOUT
element * /main/nae_phase1c/LATEST
element * /main/NAE_ROOT_PHASE1C -mkbranch nae_phase1c
element * /main/LATEST -mkbranch nae_phase1c
load \Acctsvcs

XSLT Tips / Links

know the difference between spaces in XSLT
http://www.xmlplease.com/whitespace

Eclipse Pointers / Links

- {object} cannot be resolved in Eclipse
http://blog.sherifmansour.com/?p=207

- installing plugins in Eclipse
http://www.venukb.com/2006/08/20/install-eclipse-plugins-the-easy-way

- SVN Working Copy xxx locked and cleanup failed - Right click on the project then Team -> Cleanup

- setting for debug
SET JAVA_OPTS= -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
or
set MEM_ARGS=-Xms32m -Xmx200m
set JAVA_OPTIONS=-Xverify:none -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7919

- display tool/icon for showing method only or all source
Window > Customize Perspective.... > Tool Bar Visibility > Editor Presentation > Show Source of Selected Element Only