I have a Box
class as shown below.
public class Box <E> {
private List<E> itmes = new ArrayList<>();
public void addItem(E e){
itmes.add(e);
}
public void addItemList(List<? extends E> itemList){
itmes.addAll(itemList);
}
public List<E> getItems(){
return itmes;
}
}
The first implementation uses unbounded type arguments, which works fine. As shown below
Box<Apple> appleBox = new Box<>();
Apple fujiApple = new Apple("fujiApple");
Apple kashmiriApple = new Apple("kashmiriApple");
appleBox.addItem(fujiApple);
appleBox.addItem(kashmiriApple);
Box<Orange> orangeBox = new Box<>();
Orange weirdOrange = new Orange("weirdOrange");
Orange orangeOrange = new Orange("orangeOrange");
orangeBox.addItem(weirdOrange);
orangeBox.addItem(orangeOrange);
Box<Fruit> fruitBoxAll = new Box<>();
fruitBoxAll.addItemList(appleBox.getItems());
fruitBoxAll.addItemList(orangeBox.getItems());
But now, I want to use bounded type argument as shown below
Box<? extends Fruit> fruitBox = new Box<>();
Declaring ? extends Fruit
as type argument means that List
inside Box
class will also be of type ? extends Fruit
. And following code will give an error
fruitBox.addItem(fujiApple);
As at some point later, user may try to add oranges to the same list
fruitBox.addItem(orangeOrange);
which is not right. So I cannot use this bounded type argument object to create a Box
of sub-type of Fruit
. Which is understandable from Java point of view, but then using bounded type arguments seem not useful.
So from the implementation perspective, I have following questions:
- Is using bounded type arguments a right approach?
- If Yes, What type of elements can it contain in the scenario explained above.
- Can you throw in an example, where bounded type arguments are useful or the right scenario/way to implement them.