Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Type of a Generic Type in Java?

Tags:

java

generics

I have an interface

public interface BWidgetObject<T> {
}

and I want to use this interface to create a new generic interface based on this type:

public interface BDataList<BWidgetObject> {}

The former gives a warning that the type T is hidden. The following give a compiler error:

public interface BDataList<BWidgetObject<T>> {}

How can I express BWidgetObject<T> as type parameter for BDataList?

like image 864
confile Avatar asked Mar 27 '15 12:03

confile


People also ask

What is generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is called ...

What are the advantages of generic methods and classes in Java?

It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means parameterized types.

What is generics in C++?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

What is the difference between generics and templates in Java?

Generics in Java is similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. There are some fundamental differences between the two approaches to generic types. Generic Class Like C++, we use <> to specify parameter types in generic class creation.


2 Answers

You can try with:

public interface BDataList<T extends BWidgetObject<?>> {}

Here we're specifying the the type T will be a BWidgetObject of a type we don't actually care about (and that's why we use a wildcard). We only care about T and the fact it will be a subtype of BWidgetObject.

like image 90
Konstantin Yovkov Avatar answered Oct 10 '22 07:10

Konstantin Yovkov


Use a generic bound:

public interface BDataList<T extends BWidgetObject<?>> {}

Or if you need to type the widget explicitly, you need to create another sub-interface:

public interface BWidgetDataList<T> extends BDataList<BWidgetObject<T>> {}
like image 45
Bohemian Avatar answered Oct 10 '22 09:10

Bohemian