OnJava8-Examples/references/MutableInteger.java

34 lines
894 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// references/MutableInteger.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// A changeable wrapper class
2015-06-15 17:47:35 -07:00
import java.util.*;
2017-01-21 11:39:19 -08:00
import java.util.stream.*;
2015-06-15 17:47:35 -07:00
class IntValue {
private int n;
2017-05-01 14:33:10 -06:00
IntValue(int x) { n = x; }
2015-06-15 17:47:35 -07:00
public int getValue() { return n; }
public void setValue(int n) { this.n = n; }
public void increment() { n++; }
@Override public String toString() {
2015-06-15 17:47:35 -07:00
return Integer.toString(n);
}
}
public class MutableInteger {
public static void main(String[] args) {
2017-01-21 11:39:19 -08:00
List<IntValue> v = IntStream.range(0, 10)
.mapToObj(IntValue::new)
.collect(Collectors.toList());
2015-06-15 17:47:35 -07:00
System.out.println(v);
2017-01-21 11:39:19 -08:00
v.forEach(IntValue::increment);
2015-06-15 17:47:35 -07:00
System.out.println(v);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2015-09-07 11:44:36 -06:00
*/