0

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!

user1328174
  • 533
  • 1
  • 4
  • 7
  • I think you need a generic method, so you can explicitly specify the expected return type, like here: http://stackoverflow.com/questions/590405/generic-method-in-java-without-generic-argument – mellamokb Jul 30 '12 at 22:00

1 Answers1

2

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) {
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Yes, but with a limitation as far as I remember, won't your tuple contain a list of objects with the T type instead of a list of animals? They're Animal in the end, but the list won't be able to hold both cats and dogs, for example. – Fritz Jul 30 '12 at 22:03
  • Correct. That is the goal, is it not? – cdhowie Jul 30 '12 at 22:05
  • I think he wanted to return a list of mixed particular classes rather than a list containing objects of the same type, but I can be wrong. – Fritz Jul 30 '12 at 22:09
  • Thanks! Before you showed me how to do it, I kept trying to declare T extends Animal inside the Tuple List which kept giving me compilation errors. Your answer is just what I needed! – user1328174 Jul 30 '12 at 22:11