Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Java switch over the primitive long? [duplicate]

Possible Duplicate:
Why can’t your switch statement data type be long, Java?

Why is something like that not possible?

private void importantFunction( long arg1 ) {

    switch (arg1){
    case 0:
         // do stuff
        break;
    case 1:
         // do other stuff
        break;
    default:
        //do default stuff
        break;
    }
}

The way I understand long values, there shouldn't be that much of a difference between them and integers.

like image 209
Robert Schröder Avatar asked Dec 03 '25 11:12

Robert Schröder


2 Answers

As per Java 7 you could use a String: LINK TO ORACLE

So basicly this would allow String.valueOf(23423423L);

like image 106
IDKFA Avatar answered Dec 05 '25 23:12

IDKFA


There are many, many features Java could have had. Language design is a continuous series of trade-offs between utility and complexity. Put in too many features, and the language becomes hard to learn and implement.

Obviously, one can have a long that has only a few possible values, so that it is reasonable to use it as a switch expression, but that is unusual. Mainly, long is used when there are too many values for int, and so far too many values for a switch expression.

One solution is a Map that maps the values of the long you would like to use to a small set of Integer values:

import java.util.HashMap;
import java.util.Map;

public class Test {
  public static void main(String[] args) {
    final int ONE_CASE = 3;
    final int ANOTHER_CASE = 4;
    Map<Long, Integer> map = new HashMap<Long, Integer>();
    map.put((long) 1e10, ONE_CASE);
    map.put((long) 1e11, ANOTHER_CASE);
    long arg1 = (long) 1e11;
    switch (map.get(arg1)) {
    case 3:
      System.out.println("ONE_CASE");
      break;
    case 4:
      System.out.println("ANOTHER_CASE");
      break;
    }
  }
}
like image 43
Patricia Shanahan Avatar answered Dec 06 '25 00:12

Patricia Shanahan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!