2016-08-24 16:28:10 -06:00
|
|
|
// generics/FilledList.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2016-08-24 16:28:10 -06: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-08-24 16:28:10 -06:00
|
|
|
import java.util.*;
|
|
|
|
import java.util.function.*;
|
|
|
|
import onjava.*;
|
|
|
|
|
2017-05-01 14:33:10 -06:00
|
|
|
public class FilledList<T> extends ArrayList<T> {
|
|
|
|
FilledList(Supplier<T> gen, int size) {
|
2016-08-24 16:28:10 -06:00
|
|
|
Suppliers.fill(this, gen, size);
|
|
|
|
}
|
|
|
|
public FilledList(T t, int size) {
|
|
|
|
for(int i = 0; i < size; i++)
|
|
|
|
this.add(t);
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
List<String> list = new FilledList<>("Hello", 4);
|
|
|
|
System.out.println(list);
|
|
|
|
// Supplier version:
|
|
|
|
List<Integer> ilist = new FilledList<>(() -> 47, 4);
|
|
|
|
System.out.println(ilist);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
[Hello, Hello, Hello, Hello]
|
|
|
|
[47, 47, 47, 47]
|
|
|
|
*/
|