Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java 7 Switch case for Strings - Can we use with objects which overrides equals

 
Shiv Swaminathan
Ranch Hand
Posts: 48
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeff

Can we use switch case with string feature of Java with Objects which overrides equals() and hashcode()?
Will there be any issues?

Thanks
Shiv
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, in a switch case, you can only use primitives, enum constants, and now Strings. Those are the only things allowed, and none of them allow you to override equals() or hashCode().
 
Shiv Swaminathan
Ranch Hand
Posts: 48
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm...what is the mechanics behind the switch case with string, does it do it by comparing the string values?

It will be good to have the Object version comparison too...maybe in a future Java release?
Similar to how the Object with proper overidden equals() and hascode() can be used as a key for Map.

Can we use String expressions in the switch case, an expression which returns a string value at run-time?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure of the exact mechanics, but it must compare values at some point, yes. One could analyze the bytecode to find out exactly; I don't have time at the moment.

It's certainly possible to imagine a version of switch that would allow arbitrary objects and use equals(). That's available in other languages. Java's switch tends to be designed for cases that it can execute very quickly. For anything else, it's possible to just use a series of if /else if / else statements.

For case values, you can only use constant expressions which can be fully evaluated at compile time. The argument to the switch can be an unknown variable, but the cases need to be exactly known by the compiler.
 
Shiv Swaminathan
Ranch Hand
Posts: 48
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mike.

I tried a little program which illustrates what you explained, using String constants declared in various ways:

 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And the way to see that working is not to use java com.java.explore.SwitchCase
You use
javap -c com.java.explore.SwitchCase
Then you can explore the bytecode.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic