Reputation: 97
I feel I have some wrong interpretation of Supplier use-case. Here is an example where I want to add value to a List. But when I try to fetch the list from supplier, it shows as empty.
Supplier<List<String>> str = ArrayList::new;
str.get().add("Hi");
System.out.println(str.get().size());
Returns: 0
Upvotes: 0
Views: 2769
Reputation: 45319
Supplier<List<String>>
is a function that gets invoked whenever the get
method is run.
In your case, str
is similar to the following lambda expression:
Supplier<List<String>> str = () -> new ArrayList<>();
Which means that every time str.get()
is called, the function gets called, and the body new ArrayList<>()
is executed, thus resulting in a new list every time.
If you want the Supplier
to always return the same list, then you need to capture it:
List<String> list = new ArrayList<>();
Supplier<List<String>> str = () -> list;
This way, every time str.get()
runs, it will just return the same list it captured. But, IMO, this doesn't seem like good practice, it would seem rather correct to just keep a reference to the variable instead of keeping it behind a Supplier (which implies a function producing a value).
Upvotes: 4
Reputation: 393831
Each call to str.get()
will instantiate a new List
, which will be empty.
Your two calls to str.get()
return two different instances. You added an element to the first List
, but the second List
is empty.
You have to store a reference to the created List
if you want to have access to it:
List<String> list = str.get();
list.add("Hi");
System.out.println(list.size());
Upvotes: 2