Duplicate :
|
|
Duplicate :
|
|
Duplicate :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
Name: gm110360 Date: 03/11/2004 A DESCRIPTION OF THE REQUEST : This proposal suggests changes to make the Java switch statement more useful. See: http://yost.com/computers/java/string-switch/ http://cdsmith.twu.net/professional/java/pontifications/switch.html Normally you can't use Strings or Objects in javas switch statements. I would like to use Strings in switches. Therefore I would like to see this introduced. JUSTIFICATION : It would make source code much easier and elegant. Now you would do this by using the strings hashcode instead of the strings, this has some impact on your ability to write fast code. It would also be more easy to look at the source code and understand it. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - I would like to see this implemented: switch(aString){ case "strA": //Some code } ACTUAL - Now you have to work around the limitation of using int's instead of String. ---------- BEGIN SOURCE ---------- public class SwitchTest{ public static void main(String [] args){ String input = "strA"; switch(input){ //String input, can't do this NOW case "strA": //String cases, not workable NOW System.out.println("strA"); case "strB": System.out.println("strB"); } } } ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : First you can use a container: Map strings = new HashMap(); strings.put("strA", new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Dette er strA"); } }); strings.put("strB", new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Dette er strB"); } }); String strInput = "strA"; ActionListener a = ((ActionListener) strings.get(strInput)); if (a != null) { a.actionPerformed(null); } You can also take the hashCode from the strings and do this: switch(inputString){ case 3541040: //Hashcode of "strA" System.out.println("strA"); case 3541041: //Hashcode of "strB" System.out.println("strB"); } (Incident Review ID: 243026) ====================================================================== Name: rmT116609 Date: 09/16/2004 A DESCRIPTION OF THE REQUEST : It would be nice if the 'switch' keyword could be applied to Strings and other static data types. For example, it would be nice if the following were valid Java code: public void process(String xmlTag) { switch (xmlTag) { case "rootTag": .... break; case "embededTag": .... break; case "anotherTag": .... break; } } JUSTIFICATION : This would make it so much easier to process XML where one must process differently a large number of peer tags. While this can be done with if {} else if {} statemtnts or HashMaps, the former looks ugly and the latter is not always convenient. I imagine this behaviour would find other beneficial uses too. (Review ID: 310952) ======================================================================
|