myrsnipe
myrsnipe

Reputation: 69

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.

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. 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?

Upvotes: 1

Views: 501

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201537

Like so,

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

In Java 7 (and later), you can make it shorter with the diamond operator; like so,

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

Upvotes: 5

Related Questions