0

Can I create array of suppliers? This doesn't compile somewhy:

Supplier<String>[] x = new Supplier<String>[] {
    () -> "f"
};
7
  • 2
    Better yet, use a List. Generics and arrays don't mix well because of the different approaches to variance Commented May 11, 2021 at 15:05
  • ...or if you could explain what restricts you to use an array instead of a List? Commented May 11, 2021 at 15:07
  • @Michael: The linked duplicate is really not relevant to this question. The OP asked for the array -> you suggested a List -> you linked a duplicate about creating an array of Lists. If the question should be closed as a duplicate, please refer to a more relevant existing question such as a generic array or array of lambda expressions creation. Commented May 12, 2021 at 9:26
  • @NikolasCharalambidis No. It's an exact duplicate. The problem is how to create a Foo<Bar>[]. Whether that's Supplier<String>[] or ArrayList<String>[], it doesn't matter. The problem is the same. And we don't need a question for every single built-in type which takes a single generic type parameter Commented May 12, 2021 at 9:28
  • @NikolasCharalambidis "you suggested a List -> you linked a duplicate about creating an array of Lists" You list these things as causational, but they are not. You can consider them unrelated. My advice is to use a List. But if they want to ignore my advice, then the linked duplicate has plenty of other suggestions. Commented May 12, 2021 at 9:32

2 Answers 2

3

You have to create an array of raw Supplier:

Supplier<String>[] x = new Supplier[] {
    () -> "f"
};

It's not possible to instantiate a generic array.

Sign up to request clarification or add additional context in comments.

1 Comment

.. and then good luck with Supplier<String>[] x = new Supplier[]{ () -> "f", () -> 1 };
2

You can do it like this. But it would be best to use a List.

@SuppressWarnings("unchecked")
Supplier<String>[] sups = new Supplier[]{()->"A", ()->"B", ()->"C"};

for (Supplier<String> s : sups) {
    System.out.println(s.get());
}

prints

A
B
C

This would be my preferred way of doing it. The List returned by List.of will be immutable.

List<Supplier<String>> sups = List.of(()->"A", ()->"B", ()->"C");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.