java - Why Objects cannot be used in switch statement where as enums can be used -


unlike c/c++ java enum object. enum can used in switch case statements. objects of class cannot used. there reason behind ?

switch statements compiled jump table. jump table table, defines every case statement line in code, code specific case located. example:

switch(a) {     case 0: // 0     case 1: // 1     case 2: // 2 } 

is compiled to:

lookupswitch {     0: 17     1: 33     2: 65 } ... line 17: // 0 ... line 33: // 1 ... line 65: // 2 

the nice thing jump table comparison commands omitted , can use them in array(here: { 17, 33, 65 }), omits comparisons.

because index in jump table number, cannot place function(own objects need use equals function) there. strings converted @ compile-time hash codes compare them in switch statement. enums can indexed ordinal number.

java has defined switch statements , other usages can use if/else statements.

java language reference: http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.11
java implementation reference: http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-3.html#jvms-3.10
wikipedia article jump tables: https://en.wikipedia.org/wiki/branch_table


Comments