user1328174
user1328174

Reputation: 543

java generics extension and lists

I'm trying to get the method signature correct on a utility so that I can get rid of some unchecked type casting. So far, I have:

public interface Animal {
public long getNumberLegs();
public int getWeight();
}

public class Cat implements Animal {
public long getNumberLegs() { return 4; }
public int getWeight() { return 10; }
}

public class Tuple<X, Y> {
public final X x;
public final Y y;

public Tuple(X x, Y y) {
    this.x = x;
    this.y = y;
}
}

public class AnimalUtils {
public static Tuple<List<? extends Animal>, Long> getAnimalsWithTotalWeightUnder100(List<? extends Animal> beans) {
    int totalWeight = 0;
    List<Animal> resultSet = new ArrayList<Animal>();
    //...returns a sublist of Animals that weight less than 100 and return the weight of all animals together.
        return new Tuple<List<? extends Animal>, Long>(resultSet, totalWeight);     
}
}

now I try to make a call:

Collection animals = // contains a list of cats
Tuple<List<? extends Animal>, Long> result = AnimalUtils.getAnimalsWithTotalWeightUnder100(animals);
Collection<Cat> cats = result.x;  //unchecked cast…how can i get rid of this?

the idea is that I can reuse this utility method to check dogs, rats, etc… by passing in an appropriate list of animals. I tried making all sorts of changes to the signature to the getAnimalsWithTotalWeightUnder100() method, but can't seem to get the syntax correct so that I can pass in a particular type of animal and have it return the same without the type safety issue.

Any help is greatly appreciated!

Upvotes: 0

Views: 87

Answers (1)

cdhowie
cdhowie

Reputation: 169018

If memory serves, you need to make the method itself generic, like this:

public <T extends Animal> static Tuple<List<T>, Long> getAnimalsWithTotalWeightUnder100(List<T> beans) {

Upvotes: 2

Related Questions