D
D
dostanu2020-09-21 16:20:07
Java
dostanu, 2020-09-21 16:20:07

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

1 answer(s)
C
Cheypnow, 2020-09-22
@dostanu

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.

This is the right decision, because anyway, it will be possible to store only objects of the class with which the object of the Cage class is parameterized, that is, Cage<Dog>it will not be possible to save the class object in Cat.
But it will still swear at T in the loop due to the fact that the variable is not parameterized, it is necessary: private HashMap<Long, T> animals;
​​but you can already assign it without it:
public Cage() {
     animals = new HashMap<>();
}

or no constructor at all:
private HashMap<Long, T> animals = new HashMap<>();

For example, you can add the save method:
public void save(Long k, T v) {
    animals.put(k, v);
}

If you try to create an object of the Cage class, parameterized by the Cat class, and store the Dog there, this simply will not compile:
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 question

Ask a Question

731 491 924 answers to any question