shinryu333
shinryu333

Reputation: 333

Java Generics: Can I Use an Object as a Formal Parameter?

I have just learned the concept of generics Java and trying to get some practice with it. Right now I'm trying to use an object as a formal parameter but for some reason it's not working. Here's my code:

public class Book {
    String title;  
    public Book(String s) {
        title = s;
    }   
    public String getTitle() {
        return title;
    }
    public static void main(String[] args) {
        Book book1;
        Pair<book1,int> pair1 = new Pair<>("somebook",22);
    }
}

My generic class:

public class Pair<A,B> {   
    A first;
    B second;
    public Pair(A a, B b) {
        first = a;
        second = b;
    }
    public A getFirst() { 
        return first; 
    }
    public B getSecond() { 
        return second;
    }
}

For some reason there is an error with this code line:

Pair<book1,int> pair1 = new Pair<>("somebook",22);

Any insight will be appreciated.

Upvotes: 0

Views: 52

Answers (1)

Todd
Todd

Reputation: 31710

With generics, you are always referring to types, not instances of classes. I suspect you want something like this:

Pair<Book,Integer> pair1 = new Pair<>(book1, 22);

As you can see on the left hand side, I've declared a Pair of Book and Integer. On the right, the Pair is constructed with an object that is of type Book (book1) and an integer.

Upvotes: 4

Related Questions