Posts

Showing posts with the label Java

Array Copy with Java 6

@Test public void genericArrayCopyOf() { Number[] source = { new Double(5.0), new Double(10.0) }; Number[] target = Arrays.copyOf(source, source.length); assertEquals(source, target); } @Test public void copyOfWithRange() { String[] source = { "0", "1", "2", "3", "4" }; String[] target = Arrays.copyOfRange(source, 2, 4); assertEquals(new String[] { "2", "3" }, target); } @Test public void genericArrayCopyOfWithNewType() { Number[] source = { new Double(5.0), new Double(10.0) }; Double[] target = Arrays.copyOf(source, source.length, Double[].class); assertEquals(source, target); }

Parallel class hierarchies with Java Generic

Image
import java.util.ArrayList; import java.util.Collection; /* * Super class for Habitat hierarchy */ public abstract class Habitat <A extends Animal> { /* * A generic collection that can hold Animal * or any subclass of animal */ Collection<A> collection = new ArrayList<A>(); /* * add an Inhabitant to the collection. * should be overridden by subclass */ public abstract void addInhabitant( A animal); } /* * Aquarium class inherit the collection from * Habitat superclass. But limit the collection * to Fish type. */ public class Aquarium extends Habitat <Fish> { /* * (non-Javadoc) * @see Habitat#addInhabitant(Animal) */ @Override public void addInhabitant( Fish fish) { collection.add(fish); System.out.println(Aquarium.class); } } /* * Super class for Animal hierarchy */ public abstract class Animal { } public class Fish extends Animal { } public class Test { /** * @param args */ public static...