Reputation: 73
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?
Upvotes: 7
Views: 38564
Reputation: 2867
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
void add(Object toAdd) {
Object obj = getObject();
if (obj instanceof List<?>) {
((List<Object>)obj).add(toAdd);
return;
}
throw new SomeException();
}
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:
List<String> x1 = new ArrayList<String>();
Object c3 = x1;
x1.add("asdsad");
Integer y2 = new Integer(5);
if (c3 instanceof List<?>){
((List<Object>)c3).add((Object)y2);
}
for (Object i : (List<Object>)c3){
if (i instanceof String){
System.out.println("String: " + (String)i);
}
if (i instanceof Integer){
System.out.println("Integer: "+ (Integer)i);
}
}
Upvotes: 6