Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm missing:

class SomeContainer<E>

{

    E createContents()

    {

        return what???

    }

}

1 Answer

0 votes
by (46k points)

You are right, you can't do new E(). However, in Java 8, you can apply the Supplier functional interface to accomplish this pretty easily:

class SomeContainer<E> {

  private Supplier<E> supplier;

  SomeContainer(Supplier<E> supplier) {

    this.supplier = supplier;

  }

  E createContents() {

    return supplier.get();

  }

}

You would make this class like this:

SomeContainer<String> stringContainer = new SomeContainer<>(String::new);

The syntax String::new on that thread is a constructor citation.

If your constructor uses arguments you can use a lambda expression alternatively:

SomeContainer<BigInteger> bigIntegerContainer

    = new SomeContainer<>(() -> new BigInteger(1));

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...