Java泛型:数组创建,类型转换和未检查的警告

时间:2012-09-20 18:59:29

标签: java arrays generics reflection unchecked

我有以下代码,它应该用不同数字类型的数组(Integer,Long,...)测试不同的排序算法实现(和我教授泛型)。 虽然我已经开始工作,但我想知道是否可以进行改进,特别是在我放置FIXME的3个地方。

谢谢..

package com.kash.test;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class SortTester<E extends Number> {
    E[] arr;
    E[] copyArr;
    Class<E> classOfElemType;
    int arrayLenToTestWith;

    @SuppressWarnings({ "unchecked" })
    SortTester(Class<E> cc, int ll) {
        classOfElemType = cc;
        arrayLenToTestWith = ll;
        arr = (E[]) Array.newInstance(classOfElemType, arrayLenToTestWith);
        copyArr = (E[]) Array.newInstance(classOfElemType, arrayLenToTestWith);
        for (int i = 0; i < arrayLenToTestWith; i++) {
            arr[i] = copyArr[i] = randomNumber();
        }
    }

    void reset() {
        System.arraycopy(copyArr, 0, arr, 0, arrayLenToTestWith);
    }

    E randomNumber() {
        // FIXME: Is tehre a way to do this without reflection?
        // FIXME: Also by converting the random() output to int we lose
        //        precision, anyway to avoid that without some "instanceof"
        //        kinda checks?
        try {
            // Every Number subclass, has a c'tor with a single String
            // arg, which represents an int.
            Constructor<E> ctor = classOfElemType.getConstructor(String.class);
            return ctor.newInstance(Integer.toString((int) (Math.random() * (arrayLenToTestWith * 2))));
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException
                | IllegalArgumentException | InvocationTargetException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            e.getCause().printStackTrace();
        }
        return null;
    }

    void print() {
        for (int i = 0; i < arrayLenToTestWith; i++) {
            System.out.println(Array.get(arr, i));
        }
    }

    void test(/* sorters */) {
        // test the Sorter instances on our array for time and space..
        // for s in sorters
        // do
        // // start monitors..
        // s.sort(arr);
        // // stop monitors
        // reset();
        // done
        // // print results...
    }
}

public class Main<T extends Number> {

    public static void main(String[] args) {
        // FIXME: Is tehre a way to remove the unchecked warnings for Class below? Without
        //        using "@SuppressWarnings({ "unchecked" })"
        Class types[] = { Integer.class, Double.class, Float.class, Long.class, Short.class };
        for (Class cc : types) {
            SortTester<?> typeTester = new SortTester<>(cc, 10);
            System.out.println("Type = " + cc.getCanonicalName());
            typeTester.print();
        }
        // Class<?> types2[] = { Integer.class, Double.class, Float.class, Long.class, Short.class };
        // for (Class<?> cc1 : types) {
        // SortTester<cc1> typeTester = new SortTester<>(cc1, 10);
        // typeTester.print();
        // }
    }
}

----编辑----

上面的

class旨在测试以下interface

package com.kash.src;

import java.util.Comparator;
import java.util.List;

/**
 * 
 * Interface that provides all sorting functions for all possible representations
 * of a list of Objects (non-primitive types). <br>
 * 
 * - {@link List}<{@link Comparable}><br>
 * - Array of < ? extends {@link Comparable}><br>
 * - {@link List}< ? > with external {@link Comparator}<br>
 * - Array of < ? > with external {@link Comparator}<br>
 * 
 * @author Kashyap Bhatt
 * 
 * @param <T>
 */

public interface Sorter {
    <T extends Comparable<? super T>> void sort(List<T> list);

    <T extends Comparable<? super T>> void sort(T[] array);

    <T extends Object> void sort(List<T> list, Comparator<? super T> c);

    <T extends Object> void sort(T[] array, Comparator<? super T> c);
}

1 个答案:

答案 0 :(得分:1)

作为一个很好的一般规则,当你可以使用Collection时,永远不要使用数组。

这是我初始化types变量的方式:

List<Class<? extends Number>> types = Arrays.<Class<? extends Number>>asList( Integer.class, Double.class, Float.class, Long.class, Short.class );

其余代码将保持不变。

相关问题