Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

switch with Strings

 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How can i use the switch statement using a String in the expression ?
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No you can't.
You can only use byte, short, char or Int.
You can not use long (yes),float types, boolean, objects reference(which also means string).
Regards.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's quite easy to mimic the 'switch' semantics in a polymorphic way. Construct a map an populate it with the key objects represent the 'case selectors' and associate the value part of the tuples with 'Actor' interfaces:
public interface Actor {
public void exectute();
}
Given a selector (used in the 'switch()' clause), look it up in the map; if an Actor was found, make it execute() whatever it needs to do. It's fast, and soft for your hands
kind regards
 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gustavo Adolpho Bonesso:
How can i use the switch statement using a String in the expression ?


Hi Gustavo,
It is only possible to use an int in a switch statement. However, there is a way to overcome this.
If you store all possible String values in a Vector you can use indexOf(Object) to retrieve the int index of your string for the switch statement.
e.g.

This should print out -
The 1st String
HTH,
Fintan
 
Gustavo Adolpho Bonesso
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That�s Great !
Thank you all, i have some good examples on how to do what i want...
Best Regards !
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Fintan,
IMHO, as someone who has to maintian a lot of code, your design, as functional as it is, would be a nightmare to maintain.
1) Your switch statement is dependent on the order of the vector which means if someone as SUN changes the implementation and the order isn't maintain, then this will be one really hard bug to find.
2) You solution requires creating an extra Vector object which I don't think is needed.
3) You solution doesn't handle mix-cases in the comparision.
Why don't you just use a bunch of if ... else if statments? This might not be pretty, but it's straight forward and very clear. There's no order dependency. No extra object is created, and you can handle mix case by using equalsIgnoreCase() inside the comparision.
-Peter
 
Marshal
Posts: 67522
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I heartily concur with Peter. While the vector approach may be "cool" and clever, it's not a good practice for all the reasons mentioned. Why construct an easily broken Rube Goldberg machine to do a simple job when the "if ... else if ..." idiom already exists and is conventional practice?
Just my 2 cents,
bear
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't like Fintan's Vector solution much either, but I disagree with Peter's reasons:
1) Your switch statement is dependent on the order of the vector which means if someone as SUN changes the implementation and the order isn't maintain, then this will be one really hard bug to find.
Eh? How could Sun change the implementation without violating the API? Vector has always gauranteed that it maintained the order of its elements.
2) You solution requires creating an extra Vector object which I don't think is needed.
True, but not that big a deal. The object could be declared and initialized in a static initializer to minimize overhead. (Though admittedly this will further reduce readability.)
3) You solution doesn't handle mix-cases in the comparision.
Easy enough to modify it to convert everything toLowerCase() before comparison, if you want to ignore case. This can be done in the standard idiom as well (if/else if) - it will be slightly faster than using equalsIgnoreCase() in every if. However, if you need to ignore case for some elements, but not others, then this won't work. And it is less clear than writing equalsIgnoreCase() wherever that effect is desired.
For me, the one big reason to avoid the vector technique is that the programmer(s) must maintain the relationship between the order of elements in the Vector, and the values in the case statements. Imagine what happens if you have, say, 50 different strings listed, and then later you need to modify the code to remove one of the Strings at the beginning. It's easy to delete the v.addElement("First String") and the corresponding case - but then you must also change each of the subsequent case labels too. And what if the code is edited by a co-worker who doesn't realize just how the structure operates? If he introduces an error into the case statements, it will be hard to spot without checking the whole case structure carefully. This idiom is a maintenance nightmare. (Which Peter did say - I just disagree with the further explanation.)
Also, it's worth noting that internally, the indexOf() method is just going to loop through all the elements and perform an equals() comparison until it finds a match. So indexOf() will be slightly slower than the if/else if structure since it also does the extra work of maintaining a loop index and accessing Vector elements. The switch statement may be fast - but the code before it is not.
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim,
Leave it to you to catch my far-fetch idea. You're absolutely right regarding the Vector API guarantees to maintain the order.
Regarding the second point, I thought about this but this opens a slew of issues if your code is multi-threaded.
I knew I was missing the best reason for not using Fintan's solution which was so clearly explained by you.
Thanks,
-Peter
 
Hey! You're stepping on my hand! Help me tiny ad!
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic