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".
For the second example,
int pos = Arrays.asList(getNextPos()).indexOf(getNextPos());
would allow old school switch.
It's a dirty, dirty hack, but with switch-on-string, you could:
switch (pos.toString()) {
case "1,2": ....
That does need an appropriate and stable toString method, which probably isn't a terrible idea anyway.
Even terribler:
switch (pos.x+","+pos.y) {
case "1,2": ....
Don't try the with user-supplied strings.
There have been noises from Oracle about extending instanceof pattern matching (JEP 305) into full on deconstructors for switch which could include matching on property values.
Another way around it is to use a Map from Pos to an appropriate functional type. Perhaps else-if chains aren't that bad.
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