2

When trying to compare two objects passed as arguments: first as object, second as array of objects (the same kind). Getting error Incompatible conditional operand types Room and allRooms[]. I am trying to iterate in while cycle until thisRoomType is not equals to some object from rooms. How to fix it?

public abstract class Room { ...}
public class LightRoom extends Room  {...}
public class DarkRoom extends Room {...}

Caller:

release(thisRoomType, rooms)

with parameters

private Room thisRoomType = this; // is defined in DarkRoom and LightRoom 
private Room[] rooms; // is defined in DarkRoom and LightRoom 

in method:

public synchronized void release( Room thisRoom,  Room[] allRooms) {

        try {
            int j = 0;
            while(thisRoom instanceof allRooms[j]){     
                jj++;
            }
                        int nextRoom = jj;
...
    }
}
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
  • 1
    This is an `ArrayIndexOutOfBoundsException` waiting to happen. the `while` condition must include `jj < allRooms.length` – Óscar López Apr 30 '12 at 20:10

2 Answers2

7

Try this instead:

while (j < allRooms.length && thisRoom.getClass().equals(allRooms[j].getClass()))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • @RCola sorry, you saw a previous version of my answer. Try with the updated one. – Óscar López Apr 30 '12 at 20:03
  • 2
    @ewernli I'm not sure if that's a problem. Because as stated, OP's question will _always_ loop until an `ArrayIndexOutOfBoundsException` occurs, a non-null `Room` will always be an instance of any non-null element in a `Room[]`. The code might only make sense if a different kind of room is encountered, and that's what my answer does. – Óscar López Apr 30 '12 at 20:09
  • The equivalent of instanceof is isAssignableFrom. See  http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom – ewernli Apr 30 '12 at 21:04
2

Your logic is wrong.
instanceof expects a ReferenceType while you are passing an object instance allRooms[j]. This can never work.
What you should be doing is:

  1. compare with package names or
  2. class names or
  3. compare against the concrete classes (getClass).

Pick according to your needs

Cratylus
  • 52,998
  • 69
  • 209
  • 339