Kaly
Kaly

Reputation: 99

Check and get the values of the objects

i want to get each instance for each object, i must check if one item is instance of the object, and then get the value, i have:

@Override
public void onSelection(SelectionEvent<TreeItem> event) {
 TreeItem item=event.getSelectedItem();

     if(firstGroup instanceOf TreeItem ) {
        Sun first=(Sun) item.getUserObject();
        ....;
    }
    else if(secondGroup instanceOf TreeItem) {
        Wall second=(Wall) item.getUserObject();
        ...;
    }
    else if(thirdGroup instanceOf TreeItem) {
        Sky third=(Sky) item.getUserObject();
        ...;
    }

but here work only the first if, and others don't. I need to get all values, can you please suggest me what i'm doing wrong?

Upvotes: 0

Views: 55

Answers (1)

Eran
Eran

Reputation: 393831

Don't use else if if you want all the conditions to be evaluated.

if(firstGroup instanceOf TreeItem ) {
    Sun first=(Sun) item.getUserObject();
    ....;
}
if(secondGroup instanceOf TreeItem) {
    Wall second=(Wall) item.getUserObject();
    ...;
}
if(thirdGroup instanceOf TreeItem) {
    Sky third=(Sky) item.getUserObject();
    ...;
}

else if would have made sense if all the conditions were checking the type of firstGroup, since if that was the case, only one of them could have been true for a given value of firstGroup.

After taking another look, it makes more sense to check the instance of the object you are actually casting, and in this case, else if makes sense :

if (item.getUserObject() instanceOf Sun) {
    Sun first=(Sun) item.getUserObject();
    ....;
} else if (item.getUserObject() instanceOf Wall) {
    Wall second=(Wall) item.getUserObject();
    ...;
} else  if (item.getUserObject() instanceOf Sky) {
    Sky third=(Sky) item.getUserObject();
    ...;
}

Upvotes: 3

Related Questions