Answer the question
In order to leave comments, you need to log in
How to set type for HashMap when creating a class using generic?
I want to create a Cage class in which I can store only one type of animal in HashMap. I tried passing the desired type to the constructor, setting T for the class, for each method. Everywhere one error - "Cannot resolve method 'getLegsNumber' in 'T'". That is, the method does not know that the type T is Animal and treats it as Object. The only case where the error does NOT occur is the class declaration:
But in this case, I can add both Dog and Cat to the HashMap, and I need to store objects of only one class.
public class Cage <T extends Animal>.
public class Cage <T> {
private HashMap animals;
public <T> Cage() {
animals = new HashMap<Long, T>();
}
public int getLegsAmount()
{
int amount = 0;
for (T animal : animals.values())
amount += animal.getLegsNumber();
return amount;
}
Answer the question
In order to leave comments, you need to log in
T extends Animal
But in this case, I can add both Dog and Cat to HashMap, but I need to store objects of only one class.
Cage<Dog>
it will not be possible to save the class object in Cat
. private HashMap<Long, T> animals;
public Cage() {
animals = new HashMap<>();
}
private HashMap<Long, T> animals = new HashMap<>();
public void save(Long k, T v) {
animals.put(k, v);
}
Cage<Cat> catCage = new Cage<>();
catCage.save(1L, new Cat());
catCage.save(2L, new Dog());
Required type: Cat
Provided: Dog
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question