-1

I was looking at a java code and saw the use of ... and i thought it is a replacement of []

Here is an example using ...:

public StudentData(String firstName,String lastName,double ... list)
   {
       // initialise instance variables
       this.firstName = firstName;
       this.lastName = lastName;
       this.testScores = testScores;
       this.grade = grade;
       grade = courseGrade(list); //calc 
    }

Here is an example without it:

public StudentData(String firstName,String lastName,double [] list)
   {
       // initialise instance variables
       this.firstName = firstName;
       this.lastName = lastName;
       this.testScores = testScores;
       this.grade = grade;
       grade = courseGrade(list); //calc 
    }

I tried using it in my code and it solved a few of my error messages that were previously lingering. Can you explain what the functionality of ... is vs. []

Filburt
  • 17,626
  • 12
  • 64
  • 115
A P
  • 2,131
  • 2
  • 24
  • 36

3 Answers3

1

Since Java5 we have new feature called variable arguments which help to send n number of parameters of same type but the catch is it should always be at the end of the list of parameter. You can check documentation about varargs if you want to learn more.

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
1

The only difference between

public StudentData(String firstName,String lastName,double ... list)

and

public StudentData(String firstName,String lastName,double [] list)

is that in the latter, the caller has to instantiate an array and give it as an argument. In the former, the arguments are automatically put into an array. This is called varargs.

Martin M J
  • 830
  • 1
  • 5
  • 12
0

These are so called "varargs". It is basically a replacement for an array [] and allows you to pass an arbitrary number of arguments to a method, which are automatically converted to an array of the specified type.

See the following examples:

import java.util.Arrays;

public class Varargs {

    public static void main(String[] args) {
        foo();
        bar(new String[0]);
        foo("foo");
        bar(new String[] { "foo" });
        foo("foo", "bar");
        bar(new String[] { "foo", "bar" });
    }

    public static void foo(String... strings) {
        System.out.println(Arrays.toString(strings));
    }

    public static void bar(String[] strings) {
        System.out.println(Arrays.toString(strings));
    }
}

Output:

[]
[]
[foo]
[foo]
[foo, bar]
[foo, bar]
Marvin
  • 13,325
  • 3
  • 51
  • 57