nd07
nd07

Reputation: 127

Instance generic class in other class

I have two class

class Key<T extends Comparable<T>> {// used for composite key for HashMap
 private T q;
 private T o;
 @Override
 public boolean equals(Object obj) {
    ...
 }

 @Override
 public int hashCode() {
    ....
 }
}

class A<Key,V, T> {
 private LinkedHashMap<Key,V> map;
 public A() {
  ... suppose we instance map and assign some example values for it here.
 }
 public foo (T q, T o) {
  //From two element q and o, I want to instance a object Key k
  //to check whether this key k is exist in the Map or not by using 
  //map.get(key).
  Key k = new Key(q,o);
 }
}

But I got this error "Cannot instantiate the type Key" at the line Key k = new Key(q,o)?

So why did it get this error and how can I resolve it?

Upvotes: 1

Views: 40

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

Key is being declared a type variable in class A.

class A<Key, V, T> { ...
        ^ Everything between <> are type variables

This means that when you write new Key, you are trying to create an instance of "some" class, not necessarily your Key class. Because of type erasure, the actual type is not known at runtime.

Assuming you mean to refer to your Key class as posted here, simply remove the declaration of the type variable:

class A<V, T> { ...

Note that you also should not be using raw types:

private LinkedHashMap<Key<T>,V> map;

Key<T> k = new Key<>(q, o);

Additionally, you need to bound T to conform with the constraints on Key, i.e. it must be comparable:

class A<V, T extends Comparable<T>> { ...

Upvotes: 3

Related Questions