Creating arrays of Objects in Java

Monday, December 6, 2010

You may have seen Groovy's now infamous "ArrayUtil.java" class, which contains 200+ variations on this theme:

    public static Object[] createArray(Object arg0, Object arg1, Object arg2) {
        return new Object[]{
                arg0, arg1, arg2};
    }

The authors are clear that this is a generated class whose ugliness is performance driven, and that you would never want to do such a thing in your own source code.

How would you do this in your Java? One simple approach is to use varargs:

public class VarArgsPlay {

        public static void main(String[] args) {
                VarArgsPlay v = new VarArgsPlay();
                System.out.println( v.returnArray("one","two").length );
        }
        
        public Object[] returnArray(Object... obj){
                return obj;
        }
        
}

Javabeat has a thorough treatment of this easy-to-use language feature.

No comments: