GenericArrayFactory.java


Below is the syntax highlighted version of GenericArrayFactory.java from §1.3 Stacks and Queues.


/**
 *
 * @author Dmitry Leskov
 */

import java.lang.reflect.Array;

public class GenericArrayFactory<Item> {

    public Item[] arrayOf(Class<Item[]> clazz, int length) {
        return clazz.cast(Array.newInstance(clazz.getComponentType(), length));
    }

    public static void main(String[] args) {
        Integer[] intArray = new GenericArrayFactory<Integer>().arrayOf(Integer[].class, 42);
    }
}


Copyright © 2000–2019, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 08:15:07 EDT 2022.