JDK-6404665 : 14.11: spec for switch doesn't allow wildcard of wrapper or enum
  • Type: Bug
  • Component: specification
  • Sub-Component: language
  • Affected Version: 6
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2006-03-27
  • Updated: 2015-09-17
Related Reports
Relates :  
Relates :  
Relates :  
java version "1.6.0-beta2"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0-beta2-b73)
Java HotSpot(TM) Client VM (build 1.6.0-beta2-b73, mixed mode, sharing)

The JLS 3 only allow to swicth on
char, byte, short, int, Character, Byte, Short, Integer, or an enum type (see section 14.11)
and not on type assignable without canversion in
char, byte, short, int, Character, Byte, Short, Integer, or an enum type.

With variance wilcard introduced in JDK 1.5), you can now create
subtype of final type but you can't switch on it, the code below don't
compile according to the spec.

List<? extends Integer> list=Arrays.asList(1,2);
switch(list.get(0)) {
    case 1:
    case 2:

I think the spec could be changed to let this code compile.

R����mi Forax

This bug can be reproduced always.

use a temporary variable :

List<? extends Integer> list=Arrays.asList(1,2);
int value=list.get(0);
switch() {
  case 1:
  case 2:

Technical clarification: the type of 'list.get(0)' is a capture variable, not a wildcard. This variable, CAP, has upper bound Integer, and so is a subtype of integer. The request is to change this (14.11): "The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (��8.9), or a compile-time error occurs." to this "The type of the Expression must be char, byte, short, int, ***an enum type (��8.9), or a subtype of one of Character, Byte, Short, Integer, or String***, or a compile-time error occurs." For subsequent discussion that refers to "the type of the switch statement's Expression", we would also need to define the "switch type" (or some other term) as the type from the above list which the type of the Expression matches, and then use that term instead. (In fact, the presentation of switch implicitly relies on this "switch type" concept throughout, but is somewhat confused about it. There is some type, T, to which both the Expression is converted (possibly with unboxing) and the case constants are converted (via assignment conversions).)

EVALUATION Even if we allowed '? extends Integer' to unbox to an int, there is no conversion context (JLS5) that applies to a switch's expression. A switch expression's type thus does not undergo unboxing or any other conversion. The list of acceptable types for a switch's expression is 'hard-coded' in 14.11. The list of types in 14.11 would have to be extended to include '? extends Integer', '? extends Character', "? extends Byte' and '? extends Short'. We might consider this in future, along with allowing Strings as switch expressions.