Is it possible in Java to have a switch-case statement using an object instead of primitive types?
I have a scenario where I have lots of 2d positions (x,y) and I want each of them to behave differently once they're triggered.
So for example, I would like:
Pos pos = getNextPos();
switch (pos) {
case new Pos(1, 2):
// do something
break;
case new Pos(9, 7):
// do something else...
break;
etc...
}
or perhaps
Pos pos = getNextPos();
Pos[] listOfPos = getListOfPos();
switch (pos) {
case listOfPos[0]:
// do something
break;
case listOfPos[1]:
// do something else...
break;
etc...
}
I also implemented the .equals() method in my Pos
class to return true only if both x and y are equal to the other object.
The Pos
class (with auto generated equals and hashCode):
public class Pos {
public int x;
public int y;
public Pos(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pos pos = (Pos) o;
return x == pos.x && y == pos.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
I've tried all this but when compiling I get "incompatible types: Pos cannot be converted to int".