Duplicate :
|
|
Relates :
|
|
Relates :
|
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) ======================================================================
|