简体   繁体   中英

Passing values directly to setter method using for loop

this my getter 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 for manually passing values to the setter method

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

what I want is something like this:

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

This is working on my side, is there a way to pass this values using a for loop? Also I want to know how to pass in an array as a whole?

No, you cannot pass a for-loop as values for the new test array values.

What you can do is write a sepearate function that generates an int array for you out of a 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 could then be used as such (as per the for-loop in your question):

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

Or for more simple arrays (so just a range of ints from startNumber to endNumber with an increment of 1) you could do the following:

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

The answer by nbokmans is spot on; but I suggest to step back here and have a look at your requirements.

What I mean: you should decide if you want

  • an interface that allows passing in an array as a whole
  • an interface that allows passing in single values

In other words: if it is a common thing for you to add single 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);
  }

for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM