United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: JDK-5029289 Extended switch statement accepting String arguments
JDK-5029289 : Extended switch statement accepting String arguments

Details
Type:
Enhancement
Submit Date:
2004-04-08
Status:
Closed
Updated Date:
2007-08-31
Project Name:
JDK
Resolved Date:
2007-01-12
Component:
specification
OS:
linux,windows_xp
Sub-Component:
language
CPU:
x86
Priority:
P5
Resolution:
Duplicate
Affected Versions:
1.4.2,5.0
Fixed Versions:

Related Reports
Duplicate:
Relates:
Relates:

Sub Tasks

Description
Name: jl125535			Date: 04/08/2004


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) 
======================================================================

                                    

Comments
EVALUATION

An excellent compilation scheme. May be considered for Java SE 7.
                                     
2006-10-27



Hardware and Software, Engineered to Work Together