MyUserQuestion
MyUserQuestion

Reputation: 295

Java generic class syntax

I know that I can create a class in java like this:

public class test {/*some code*/}

But now I have this:

public class coada < T extends Number & Comparable < Number>> {
    List <T> pq = new ArrayList <T>();

    public void add(T e , List <T> c) {
        c.add(e);
        Collections.sort(c);
    }

    public void remove(List < ? extends Number> c) {
        c.remove(0);
    }
}

I don't understand the more complicated syntax of the angled brackets and parameter lists.

I have these questions:

  1. Can someone clarify the syntax used in the example?

  2. I know Java doesn't support multiple inheritance. So how are Number & Comparable possible?

  3. I thought generics are used for collections, not classes, so, how can class coada have a type parameter?

Upvotes: 1

Views: 97

Answers (2)

Eran
Eran

Reputation: 393781

Comparable is an interface, so T can extend Number and implement Comparable<Number> (and any number of other interfaces) at the same time.

As for your second question, any class can have type parameters, not only Collections. coada < T extends Number & Comparable < Number>> means that the class coada has a type parameter called T which must be either Number or a sub-class of Number and implement the interface Comparable<Number>.

Upvotes: 1

dbf
dbf

Reputation: 6499

  1. T extends Number & Comparable <Number> T extends Number and implements Comparable

  2. Generics don't require type to be a collection.

Upvotes: 2

Related Questions