I know java doesn't support switching on a String.
Is this allowed?:
is this seen as a bad way,...?Code:switch("lol".hashCode()){
case "funny".hascode:
...
Printable View
I know java doesn't support switching on a String.
Is this allowed?:
is this seen as a bad way,...?Code:switch("lol".hashCode()){
case "funny".hascode:
...
thats the problem.
but is there another solution except if,else if, else if ,...?
enums, perhaps? Or perhaps a HashMap<String, YourInterface>, although the latter would depend on the hashcode of the String again.
I've heard of talk of java 7 allowing switch statements with String, but don't know for sure. Let's see if anyone more expert knows more.
Well, there are a few proposals, this is one of them; imho they don't buy you much except for a bit of syntactic sugar.
kind regards,
Jos
Why do you need this switch on strings?
A redesign of your solution might also help. e.g using command pattern for your action/events. Just thought that if you explain the problem you might be guided to a better solution.
but still, your not garanteed that it will be the right string he selected,isn't it?
It would be a nasty bug to track down.
there is no possibility other then using else if?
Most things in java have the source code in the src.zip file, is the switch statement scripted over there?(which would be strange because switch isn't an object and probably isn't there)
sorry for any spelling mistakes, I am not a native speaker
[qoute]
but still, your not garanteed that it will be the right string he selected,isn't it?
It would be a nasty bug to track down.
there is no possibility other then using else if?
Most things in java have the source code in the src.zip file, is the switch statement scripted over there?(which would be strange because switch isn't an object and probably isn't there)
sorry for any spelling mistakes, I am not a native speaker
[/qoute]
If you use the Map like suggested then you don't need the else if.
Just something like
Code:String testValue = ...;
Runnable someCode = map.get(testValue);//returns the Runnable mapped to testValue
someCode.run();//or thread start it
my problem:
String prefix;
switch(prefix){
case "server-message":
case "broadcast-message":
case "private-message":
...
But I heard hash codes aren't identicall so I am asking if there's another possibiltiy
Did you read replies that are suggesting that you use a map of Runnables?
yes,I did.
I was asking for other posibilities
Without actually knowing what it is you're doing we're not necessarily going to give you the best answer, though you've been given a good option above with the Map/Runnable.
If you're switching on this prefix to decide how to process the message I'd suggest having different message types represented by different Message subclasses, but you'd still have to actually create the Message, which would still involve looking at that prefix String.