对象初始化语法:somevar =(someclass [])对象[avariable]



在以下代码段中,来自https://introcs.cs.cs.princeton.edu/java/44st/binarysearchst.java.java.htmlkeys = (Key[]) new Comparable[initCapacity];做什么?

public class BinarySearchST<Key extends Comparable<Key>, Value> {
    private static final int INIT_SIZE = 8;
    private Value[] vals;    // symbol table values
    private Key[] keys;      // symbol table keys
    private int n = 0;       // number of elements
    public BinarySearchST() {
        this(INIT_SIZE);
    }
    public BinarySearchST(int initCapacity) {
        vals = (Value[]) new Object[initCapacity];
        keys = (Key[]) new Comparable[initCapacity];
    } ...

您可以像这样分解它:

初始化 new Object size initCapacity

的阵列
Object [] someValues = new Object[initCapacity];
Comparable [] someComparable = new Comparable[initCapacity];

然后将数组输入到类型Value

的数组
vals = (Value[]) someValues;
keys = (Keys[]) someComparable;

您上面的声明是在单行上进行这些操作。请记住,您已将vals声明为Valueskeys的数组,为Keys的数组。

在这种情况下, Key是一种通用类型。具体来说,是某种类型的延伸Comparable

由于由于类型擦除而无法创建通用类型的数组,因此您需要创建该通用类型的Supertype/接口的数组。在这种情况下,我们知道Comparable是通用类型Key的接口,因此在内存中创建了Comparables的数组,然后铸造为通用类型Key

这里有更多示例(也实现可比):

static <T extends Comparable> T[] genericMethod(T someObj) {
    T[] arrayOfTypeT = (T[]) new Comparable[1];
    arrayOfTypeT[0] = someObj;
    return arrayOfTypeT;
}
// String extends Comparable
public static void main(String[] args) {
    String[] arrayOfString = genericMethod("A string");
    Integer[] arrayOfInt = genericMethod(new Integer(1));
    // this one doesn't compile, because it doesn't extend Comparable
    Object[] arrayOfObject = genericMethod(new Object());
}

最新更新