Posts

Showing posts from May, 2014

Java Trick: Generic Array Converter

I had a problem of increasing size of the array. Of course I have to copy the array. But it is not easy with java Generics, because of the following problem: public class ArrayUtils<T>{ public T[] resizeArray(T[] source, int offset){ int length = source.length+offset; Object[] aNew = new Object[length]; System.arraycopy(source, 0, aNew, 0, source.length); return (T[])aNew; } } Of course you can compile the ArrayUtils class, but you cannot use this method as shown in the following code segment: public static void main(String[] args){ Integer[] ints = new Integer[2]; ints[0]=0; ints[1]=1; Integer[] newInts = new ArrayUtils<integer>().resizeArray(ints, 3); System.out.println(newInts.length); } Here the error: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at net.au.abc.abcid.test.ArrayCopyTest.main(ArrayCopyTest.java:9) the problem, aNew never is possible to cast t

Java Trick: Double brace initialization

This is a trick I found from the Core Java™: Volume I—Fundamentals, Ninth Edition, 6.4.6. Anonymous Inner Classes. import java.util.ArrayList; import java.util.List; public class TestArrayList { private String s1; private static String s2; public static void main(String[] args) { TestArrayList tl = new TestArrayList(); tl.printList(new ArrayList (){ {add("a"); add("b"); add(s2);} }); } public void printList(/*only final variables are accessible to local inner classes*/final List sList){ printDynamicList(new ArrayList (){{add(s1); addAll(sList);}}); } public void printDynamicList(List dList){ } } As shown in the above code: As shown in the line# 10, you can add elements to the anonymous array: this is called Double brace initialization. Again in the line# 16, in the double brace initialization, s1 is added to the array which is a property fo the outer class. To add the parameter in line# 16, it should be final, this is the rule of l