Reputation: 13614
Here is my Java code:
import java.util.HashMap;
import java.util.Map;
public class Polynomial<K> {
Map<Integer, Object> polynomial;
public Polynomial(){
polynomial = new HashMap<K, V>();
}
public Polynomial(int numberOfMembers){
polynomial = new HashMap<K, V>(numberOfMembers);
}
public void addElm(int power, int coefficient){
if (power < 0) {
power = Math.abs(power);
throw new RuntimeException("ERROR: The power must be an absolute number, converting to absolute");
}
for (Map.Entry m : polynomial.entrySet()) {
if ((Integer) m.getKey() == power){
polynomial.put(power,m.getValue());
}
}
}
}
On this two rows:
polynomial = new HashMap<K, V>();
and this:
polynomial = new HashMap<K, V>(numberOfMembers);
I get this error:
HashMap<K,V> cannot be resolved to a type
Any idea what cause to the error above and how to fix it?
Upvotes: 2
Views: 33774
Reputation: 2479
I don't think you actually intend to use the generics you are have.
When you create a new HashMap<K,V>()
, those <K,V>
values are the actual class names for the types that the HashMap will hold. In your case, those types are Integer and Object so you should write new HashMap<Integer, Object>()
.
Even that is unnecessary however because Java can infer the type of the HashMap since you have already defined it once. It is best to just use new HashMap<>();
public class Polynomial {
Map<Integer, Object> polynomial;
public Polynomial() {
polynomial = new HashMap<>();
}
public Polynomial(int numberOfMembers) {
polynomial = new HashMap<>(numberOfMembers);
}
public void addElm(int power, int coefficient) {
if (power < 0) {
power = Math.abs(power);
throw new RuntimeException("ERROR: The power must be an absolute number, converting to absolute");
}
for (Entry<Integer, Object> m : polynomial.entrySet()) {
if ((Integer) m.getKey() == power) {
polynomial.put(power, m.getValue());
}
}
}
}
Upvotes: 4
Reputation: 25903
You write Map<Integer, Object> polynomial;
. This means polynomial
is a Map
that needs Integer
and Object
but then you assign polynomial = new HashMap<K, V>();
. The class K
and V
are not Integer
and Object
thus the error.
You could write
polynomial = new HashMap<Integer, Object>();
then it would work. What are the types you actually want? Why did you even wrote K, V
in the first place? Or else, why the Integer, Object
, why not stick to K
and V
? And also, if you would like to hold V
generic you need to add it to class Polynomial<K, V>
too.
Upvotes: 2