I have an Object that sometimes contains a List<Object>. I want to check it with instanceof, and if it is, then add some elements to it.
void add(Object toAdd) {
Object obj = getValue();
if (obj instanceof List<?>) {
List<?> list = obj;
if (list instanceof List<Object>) { // Error
((List<Object>) list).add(toAdd);
} else {
List<Object> newList = new ArrayList<Object>(list);
newList.add(toAdd);
setValue(newList);
}
return;
}
throw new SomeException();
}
And it says I can’t check if it is instanceof List<Object> because java doesn’t care and erased the type in <>.
Does this mean I have to create new ArrayList every time? Or is there a way to check that, eg. with reflection?
I was wrong in my previous answer since i not fully understood your requirements.
if your added item is an Object you may add it without any problem as long as you Have a list of something.
You don’t have to recreate the list
UPDATE
as answer to few comments, there is no problem to add any object to a list, and there is no problem to find out what type of object it is during iteration after it: