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?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
This could be used if you want to check that object is instance of List<T> , which is not empty: if(object instanceof List){ if(((List)object). size()>0 && (((List)object). get(0) instanceof MyObject)){ // The object is of List<MyObject> and is not empty.
The JavaScript instanceof operator is used to check the type of an object at the run time. It returns a boolean value(true or false). If the returned value is true, then it indicates that the object is an instance of a particular class and if the returned value is false then it is not.
To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With