I have a question regarding type generics and lists. I'm still pretty new to type generics so this maybe a stupid question :D
So... I have an abstract class called "Map" which contains an ArrayList of elements which extend from the class "BaseElement" like so:
private final ArrayList<? extends BaseElement> elements;
In this class I also have a method called "addElement" to add an element to that list, while also returning the element back:
protected <T extends BaseElement> T addElement(T element) {
elements.add(element);
return element;
}
I don't know why I can't add this element to the list... The type specified for the "addElement" method is extending BaseElement so the element should also be extending from BaseElement, right?
I also have a "getElement" method which should return an element with it's original type (not BaseElement) from the elements list, which currently looks like so:
public BaseElement getElement(int elementID) {
return elements.stream()
.filter(element -> element.getID() == elementID)
.findFirst()
.orElse(null);
}
Are type generics even the right thing for the job or should I use another technique?
Here is the code mentioned here in it's entirety, which gives a lot more info to this question: https://gist.github.com/Akjo03/8758429c37332688a78a73aa7317569f