Reputation: 145
private void createObject(List<Activities> listOfActivities){
ABC object1 = new ABC();
String value = "";
if (listOfActivities instanceof XYZ) {
for (Activities list: listOfActivities) {
value= ((XYZ) list).getValue();
}
object1.setValue(value)
listOfActivities.add(object1);
}
}
In this method, listOfActivities has some values of Type XYZ. So 'if' block should execute which is checking if listOfActivities is an instance of class XYZ, but its not executing. Why?
Thanks in advance.
Upvotes: 0
Views: 40
Reputation: 338496
A List<String>
is of type List
, not String
.
So your List<Activity>
is of type List
and will return false
for instanceof Activity
.
The objects you retrieve from the list will be of type Activity
.
For this scenario:
List< Activity > list = new ArrayList<>() ;
list.add( new Activity() ) ;
…let’s try:
boolean isListAnActivity = list instanceof Activity ; // false
boolean isElementOfListAnActivity = list.get( 0 ) instanceof Activity ; // true
See this code run live at IdeOne.com.
isListAnActivity: false
isElementOfListAnActivity: true
Upvotes: 1