6

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

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);
    }
}
4

1 回答 1

5

我之前的回答错了,因为我没有完全理解你的要求。如果您添加的项目是一个对象,您可以毫无问题地添加它,只要您有一个列表。您不必重新创建列表

void add(Object toAdd) {
    Object obj = getObject();
    if (obj instanceof List<?>) {
        ((List<Object>)obj).add(toAdd);
        return;
    }
    throw new SomeException();
}

更新

作为对少数评论的回答,将任何对象添加到列表中是没有问题的,并且在它之后的迭代期间找出它是什么类型的对象也没有问题:

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);
    }
}
于 2013-02-03T15:51:55.797 回答