简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM