有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重写比较程序(T)

我做了一个名为“People”的类。 现在我想用TreeSet比较两个对象

public class People<T> implements Comparable<T> {

    public TreeSet<People> treeSet;
    public String name;

    public People(String name)
    {
        treeSet =  new TreeSet();
this.name = name;
    }

@Override
    public int compareTo(T y) {

        if(this.name.equals(y.name)) blablabla; //Here I get error 
    }

错误:

Cannot find symbol
symbol: variable name;
location: variable y of type T
where T is a type variable 
T extends Object declared in class OsobaSet

有人知道如何解决这个问题吗


共 (1) 个答案

  1. # 1 楼答案

    {}接口中的泛型类型代表要比较的对象的类型

    这是您的示例的正确用法:

    public class People implements Comparable<People>
    

    在这种情况下,将使用方法签名

    @Override
    public int compareTo(People y) {
        if (this.name.equals(y.name))  { ...
    }