简体   繁体   English

如何实现Java通用数据结构,避免类型擦除强制转换问题

[英]How to implement a java generic data structure, avoiding type erasure casting issues

I have the following code: 我有以下代码:

public class Matrix<K, V> {
    private final List<K> colKeys;
    private final List<K> rowKeys;
    private final Map<K, Map<K, V>> matrix;

    public Matrix() {
        colKeys = new LinkedList<>();
        rowKeys = new LinkedList<>();
        matrix = new TreeMap<>();
    }

    ...

    public V getCell(K row, K col) {
        return matrix.get(row).get(col);
    }

    ...

}

And I access it like this in another class like this: 我在另一个这样的类中访问它:

Matrix matrix = new Matrix<String, Double>();

...

for (String colKey : colKeys) {
    double sum = 0;
    int divider = 0;

    for (String rowKey : rowKeys) {
        if (matrix.containsCell(rowKey, colKey)) {
            sum += (double)matrix.getCell(rowKey, colKey);
            divider++;
        }
    }
}

Notice that I'm forced to cast the returned value of getCell(K row, K, col) to double as the compiler will tell me it returns a java.lang.Object without it. 请注意,我被迫将getCell(K row, K, col)的返回值强制转换为double因为编译器将告诉我它返回一个不带它的java.lang.Object

I'm pretty certain this is due to type erasure. 我可以肯定这是由于类型擦除引起的。 Java has quite a few data structures that uses generics, yet there's no need to cast values. Java有很多使用泛型的数据结构,但是不需要强制转换值。 Looking at the implementations of a few of these data structures I'm still at a loss as of how they solve this. 看看其中一些数据结构的实现,我对它们如何解决这个问题仍然不知所措。

So, my question is: How do you make data structure that implements generics in such a way that there is no need to cast a returned value? 因此,我的问题是:如何构建无需泛型返回值的实现泛型的数据结构?

Like so, 像这样

Matrix<String, Double> matrix = new Matrix<String, Double> ();

In Java 7 (and later), you can make it shorter with the diamond operator; 在Java 7(及更高版本)中,可以使用菱形运算符将其缩短。 like so, 像这样

Matrix<String, Double> matrix = new Matrix<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM