rizz
rizz

Reputation: 41

Eliminating redundancy in Java Constructor

I have a constructor i'm trying to condense down in my assignment.

public int[] StudentIds;
public Students(int[] a) 
{
    StudentIds = a;
}

public static void main(String[] args)
{
    Students s1 = new Students(new int[] {123, 456, 789});

the line i'm wondering about is for the Students(int[] a) and then having to toss a into it for student ids. Is there a way to do this in the original brackets/parenthesis of Students() ? or do I have to kind of flow it out like this?

Upvotes: 2

Views: 140

Answers (3)

Michał Zegan
Michał Zegan

Reputation: 466

Well, there exists something like varargs parameters for methods and constructors. So, you can do like:

public Students(int ...a) 
{
    StudentIds = a;
}

Upvotes: 0

Nir Levy
Nir Levy

Reputation: 12943

you can use the ... varargs, as described here

if you'll do:

public Students(int... students) {
}

students will be assigned with an array of ints when called:

new Students(1,2,3);

Upvotes: 1

Arhowk
Arhowk

Reputation: 921

You could use a variable argument specifier

public Students(int ... a){
      //a can be accessed like an int array

than you can call

 Students s1 = new Students(5,3,1)

to construct without the int[]{} call

Upvotes: 4

Related Questions