Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-5024518

need warning if varargs argument isn't boxed

XMLWordPrintable

    • b49
    • x86, sparc
    • solaris_2.6, solaris_8, windows_2000


      J2SE 1.5 includes "varargs" support. In general this causes
      autoboxing of varargs arguments into an Object[]. However
      there are some special cases where if a single varargs argument
      is passed then it is passed verbatim. (This is necessary for
      backwards compatibility.)

      This is potentially confusing to developers who may expect
      that all varargs arguments will always be auto-boxed.

      For exmaple, if you pass a single varargs argument of type null
      or of type String[] then the value doesn't get boxed.

      See a small test case below. This generates the output:

          "none" x0 { }
          "1" 1 { 1 }
          "null" null
          "array of two strings" 2 { one two }

      This indicates that the first two calls on doStuff are getting
      boxed into arrays, but in the third and fourth calls the exact
      arguments is being passed without boxing.

      public class VarArgs {

          static java.io.PrintStream out = System.out;

          private static void doStuff(String mess, Object... args) {

              out.printf("\"%s\"", mess);
              if (args == null) {
                  out.printf(" null\n");
                  return;
              }
              out.printf(" %d {", args.length);
              for (Object arg: args) {
                 out.printf(" %s", arg);
              }
              out.printf(" }\n");
          }


          public static void main(String argv[]) {
              doStuff("none"); // Boxing occurs OK.
              doStuff("1", 1); // Boxing occurs OK.


              doStuff("null", null); // No boxing occurs.

              String strings[] = { "one", "two" };
              doStuff("array of two strings", strings); // No boxing occurs
          }
      }


      As suggested by Neal, the right answer seems to be to provide
      a compiler warning for the problematic cases.

      ###@###.### 2004-03-31

            gafter Neal Gafter (Inactive)
            ghamiltosunw Graham Hamilton (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: