Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 5029289
Votes 2
Synopsis Extended switch statement accepting String arguments
Category java:specification
Reported Against 1.4.2
Release Fixed
State 11-Closed, duplicate of 5012262, request for enhancement
Priority: 5-Very Low
Related Bugs 4276296 , 4811993
Submit Date 08-APR-2004
Description


A DESCRIPTION OF THE REQUEST :
It is quite common requirement to dynamically return items according to their respective strings. e.g.

Object Example
{
  private Integer id;
  private String name;
  private Object value;

  public Object getProperty(String name)
  {
    if (name.equals("id")) {
       return this.id;
    }
    if (name.equals("name")) {
       return this.name;
    }
    if (name.equals("value")) {
       return this.value;
    }
   return null;
 }
}

This approach is very straightforward and works quite nicely for small amount of items. However, when the amount items increases:

- the performance remains linear (N/2)
- chained if statements look ugly
- with high number of items one is forced to create Map's with "binder" classes

There exists a simple and elegant solution; extended switch statement accepting Strings arguments:


  public Object getProperty(String name)
  {
    switch(name)
    {
    case "id":
       return this.id;

    case "name":
       return this.id;

    case "value":
       return this.id;
  
   default:
     return null;
   }
 }

javac would produce following (pseudo)code:

  public Object getProperty(String name)
  {
    switch(name.hashCode())
    case 0xd1b:
    {
      if (name.equals("id")) {
         return this.id;
      }
    }
    goto default;

   case 0x337a8b:
    {
      if (name.equals("name")) {
        return this.name;
      }
    }
   goto default;

  case 0x6ac9171:
   {
     if (name.equals("value")) {
       return this.value;
     }
   }
   goto default;

   default:
     return null;
   }
 }

For the String lookups this approach is fastest possible; "compile time hashtable".





JUSTIFICATION :
Given that the 1.5 is going to contain small features like autoboxing and enhanced for loop this enhancement would fit nicely to that bunch.
(Incident Review ID: 232974) 
======================================================================
Posted Date : 2006-10-27 14:20:37.0
Work Around
N/A
Evaluation
An excellent compilation scheme. May be considered for Java SE 7.
Posted Date : 2007-01-12 12:39:46.0
Comments
  
  Include a link with my name & email   


PLEASE NOTE: JDK6 is formerly known as Project Mustang