有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的泛型数组元素为空?(正在尝试将元素复制到新数组中)

我有一个symbol table类,它使用两个通用且可比较的数组,键[]和值[]。在main()中,我读取输入(一个文本文件),并相应地填充符号表数组。我正在尝试创建一个方法,其中我想将Value[]vals复制到一个新数组中。但是,与键[]键一起构成符号表的my vals[]元素打印为空。为什么我会变空,更重要的是,解决这个问题的一般方法是什么

由于符号表已经实例化,数组随后由put()填充,我希望vals[z]包含一些可用于复制到另一个数组中的整数值,但整个数组为空?下面省略了一些代码,显示了主要函数put()、get()和rank()

public class SymbolTable<Key extends Comparable<Key>, Value extends Comparable<Value>> {
    private Key[] keys;
    private Value[] vals;
    private int N = 0;

    // problem here when trying to copy generic arrays
    public void function(int x, int y){
        // Copy vals into valscopy
        Value[] valscopy;
        valscopy = (Value[]) new Comparable[vals.length];
        for(int z = 0; z < valscopy.length; z++){
            valscopy[z] = vals[z]; 
        }


        for(int i = valscopy.length-1; i >= valscopy.length-((y-x)+1); i--){
            StdOut.println(valscopy[i] + " " + vals[i]); <------ both print null
        }
    }



    public SymbolTable(int capacity)
    {
        keys = (Key[]) new Comparable[capacity];
        vals = (Value[]) new Comparable[capacity];
    }

    public Value get(Key key) {
        if (isEmpty()) {
            return null;
        }
        int i = rank(key);
        if (i < N && keys[i].compareTo(key) == 0) {
            return vals[i];
        } else {
            return null;
        }
    }


    public void put(Key key, Value val) {
        int i = rank(key);
        // if the same key is found, update value
        if (i < N && keys[i].compareTo(key) == 0) {
            vals[i] = val;
            return;
        }
        // make room for new key,value pair to be inserted at position i
        for (int j = N; j > i; j--) {
            keys[j] = keys[j - 1];
            vals[j] = vals[j - 1];
        }
        // insert key and value
        keys[i] = key;
        vals[i] = val;
        N++;
    }

    public int rank(Key key) {
        int lo = 0, hi = N - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int cmp = key.compareTo(keys[mid]);
            if (cmp < 0) {
                hi = mid - 1;
            } else if (cmp > 0) {
                lo = mid + 1;
            } else return mid;
        }
        return lo;
    }

    boolean contains(Key key) {
        return get(key) != null;
    }
    public int size() {
        return N;
    }
    boolean isEmpty() {
        return size() == 0;
    }

    public static void main(String[] args) {

        SymbolTable<String, Integer> st = new SymbolTable<String, Integer>(2000);

        String word = "";

        while (!StdIn.isEmpty()) { 

            word = StdIn.readString(); // Read words/keys 
            if (!st.contains(word)) st.put(word, 1); 
            else st.put(word, st.get(word) + 1); 
        }

        st.function(3, 7);
    }
}

共 (0) 个答案