4 February 2009

Using Strings and Objects in Switch case statements.

Lets consider enhancement on Sun Bug Database : 5012262

It's about letting us using String in switch.

Sample workaround:

switch(inputString.hashCode()){
 case 3541040: //Hashcode of "strA"
  System.out.println("strA");
 case 3541041: //Hashcode of "strB"
  System.out.println("strB");
}

Now let's see why this will do not work:
System.out.println("aa".hashCode());
System.out.println("bB".hashCode());
Will result with:
3104
3104

Quite lol?

So finally lets see more interesting workaround:

enum Switch {

    ONE("asd") {
      @Override
      public void action() {
        System.out.println(this.text);
      }
    },//
    TWO("bad");//

    protected String  text;

    public void action() {
      throw new NotImplementedException();
    }

    Switch(String text) {
      if (text == null) { throw new NullPointerException("text"); }
      this.text = text;
    }

    public static Switch getByText(String text) {
      if (text == null) return null;
      for (Switch casee : Switch.values()) {
        if (casee.text.equals(text)) return casee;
      }
      return null;
    }

    public static Switch getByTextForStartWith(String prefix) {
      if (prefix == null) return null;
      for (Switch casee : Switch.values()) {
        if (casee.text.startsWith(prefix)) return casee;
      }
      return null;
    }

  }

Can we?
Sure we can!

@see: String switch: Small language changes on JDK 7

0 comments / komentarz(y):

Post a Comment