Passing values ​​directly to setter method using for loop

this my receiver and setter:

private int[] test;

public int[] getTest() {
    return Arrays.copyOf(test, test.length);
}

public void setTest(int[] test) {
    this.test= Arrays.copyOf(test, test.length);
}

      

And here is my code to pass values ​​to the pass method manually

Sample sample = new Sample();   
sample.setTest(new int[]{0,1,2,3});

      

i want something like this:

for (int i = 0; i < 3; i++) {
    //code here for passing the value to the setter
}

      

This works on my side, is there a way to pass these values ​​using a for loop? Also I want to know how to pass the array as a whole?

+3


source to share


2 answers


No, you cannot pass values for-loop

as values ​​for new array values test

.

What you can do is write a sepearate function that generates an int array for you from for-loop

:

public int[] getNumbers(int start, int end, int increment) {
    List<Integer> values = new ArrayList<>(); 
    for (int i = start; i < end; i += increment) {
        values.add(i);
    }
    return values.stream().mapToInt(i->i).toArray();
}

      

which can then be used as such (as for-loop

per your question):



sample.setTest(getNumbers(0, 3, 1));

      

Or for simpler arrays (so only int range from startNumber to endNumber in increments of 1) you can do the following:

sample.setTest(IntStream.rangeClosed(1, 10).toArray());

      

+2


source


Nbokmans answer is a point; but I suggest coming back here and looking at your requirements.

What I mean is: you have to decide if you want

  • an interface that allows you to pass in an array as a whole
  • interface that allows the transfer of single values


In other words: if it's a common thing to add individual values ​​to that field ... then you should design your interface accordingly. Like this:

public class Whatever {
  private final List<Integer> data = new ArrayList<>();

  public void append(int value) {
    data.add(value);
  }

  public void getData() {
    return new ArrayList<>(data);
  }

      

eg.

+1


source







All Articles