DrJessop
DrJessop

Reputation: 472

Returning the same type As Supplied as an Argument - Java8 Generics

I'm supposed to write a generic method called getLowCost that takes two arguments : An array list arLst1 that is either type Battery, Single Use, or Rechargeable, and a double cost. I'm supposed to return an array list of all batteries in arLst1 that have a cost less than or equal to the cost supplied.

I thought I would begin like this,

public ArrayList<? extends Battery> getLowCost(ArrayList<? extends Battery> list, double val) {
    ArrayList<? extends Battery> list2 = new ArrayList<>();
    for (Battery obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
}

Unfortunately, I cannot add the object to my my list2. How can I guarantee that the return type has the same type as the first argument?

Upvotes: 0

Views: 30

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

Use a type variable:

public <T extends Battery> ArrayList<T> getLowCost(ArrayList<T> list, double val) {
    ArrayList<T> list2 = new ArrayList<>();
    for (T obj: list) {
        if (obj.getLifeTimeCost() < val) {
            list2.add(obj);
        }
    }
    return list2;
}

Upvotes: 3

Related Questions