简体   繁体   English

重写泛型equals方法

[英]Overriding generic equals method

To preface this, I've looked for numerous examples prior to asking and can't find any solution in regards to my problem. 为此,在提出问题之前,我已经查找了许多示例,但针对我的问题找不到任何解决方案。

I'm trying to implement a generic queue in a program I'm making, but stuck at a certain point. 我正在尝试在正在制作的程序中实现通用队列,但遇到了问题。 The program I've made is supposed to simulate a printer, queued with print jobs. 我制作的程序应该模拟一台打印机,排队等待打印作业。 There is a Queue class, PrintQueue class, and job class. 有一个Queue类,PrintQueue类和job类。 (It is important to note the Job class consists of a job ID and String of who ordered it). (重要的是要注意Job类包括一个工作ID和订购它的字符串)。 I've included a function (in the printQueue class) where if the first job matches the job ID you put in, it will be deleted. 我在printQueue类中包含了一个函数,如果第一个作业与您放入的作业ID相匹配,它将被删除。

Unfortunately however, the queue is generic. 但是不幸的是,队列是通用的。 This means I can't traverse the array with just an integer to check equality because it is a queue of job objects . 这意味着我不能用一个整数遍历数组来检查是否相等, 因为它是一个作业对象队列 To fix this I create a job with a blank name, and regular ID. 为了解决这个问题,我创建了一个空白名称和常规ID的作业。 The Job class has an equals method, which determines if either ID or Owner match, then it is true. Job类具有一个equals方法,该方法确定ID或Owner是否匹配,则为true。 But when I execute the code, this class is not called. 但是,当我执行代码时,不会调用此类。 The generic equals class is called instead, which will of course be false. 相反,将调用泛型equals类,这当然是错误的。 After looking at many examples on this site, I tried all the recommended solutions, which did not work for me as my case (and problem) are different. 在查看了该站点上的许多示例之后,我尝试了所有推荐的解决方案,但由于我的情况(和问题)不同,因此这些解决方案对我不起作用。 What can I do to override the generic equals method? 我该怎么做才能覆盖泛型equals方法? My code below is as simple as I could make it to reproduce this problem while keep context. 下面的代码很简单,只要保留上下文即可重现此问题。

JOB CLASS 工作班

public class Job{
    private String owner;
    private int jobId;

    public Job(String o, int j){
        owner = o;
        jobId = j;
    }
    public String getOwner(){
        return owner;
    }
    public int getJobId(){
        return jobId;
    }
    public String toString() {
        return owner + "    " + jobId + ".  ";
    }

    public boolean equals(Job a) {
        if(this.jobId == a.getJobId() || this.owner.equals(a.getOwner())) {
            return true;
        }
        else
            System.out.println("nomatch");
            return false;
    }
}

GENERIC QUEUE CLASS 一般队列类

   import java.util.ArrayList;
   public class Queue<T>{
    private ArrayList<T> queue;
    public Queue() {
        queue = new ArrayList<T>();
    }
    public void enQueue(T obj1) {
        queue.add(obj1);
    }
    public T deQueue() {
        if(queue.size() != 0) {
            T temp = queue.get(queue.size() - 1);
            queue.remove(queue.size() -1);
            return temp;
        }
        else
            return null;
    }
    public int size() {
        return queue.size();
    }
    public boolean isEmpty() {
        if (size() == 0) {
            return true;
        }
        else
            return false;
    }
    public int positionOf(T a) {
        for(int x = 0; x < queue.size(); x++) {
            if(a.equals(queue.get(x))) {
                System.out.println("Positionmatch");
                return x;
            }
        }
        return -1;
    }
}

PRINTQUEUE CLASS 列印类

public class PrintQueue {
    Queue<Job> prqueue = new Queue<Job>();
    public PrintQueue() {}

    public void lprm(int jobID) { //Removes the active job at the front of the queue if jobId matches, error message otherwise
        //I can't JUST use jobID to check the position because the queue is a collection of JOBS not JobId's
        if (prqueue.positionOf(new Job("",jobID))==0) {
            prqueue.deQueue();
        }
        else if (prqueue.positionOf(new Job("",jobID))== -1) {
            System.out.println("Job does not occupy first row.");
        }
    }
}

I know this is an extensive question, so if you do take the time to read it thank you very much. 我知道这是一个广泛的问题,因此,如果您花时间阅读它,则非常感谢。 I wouldn't ask this if I could find the answer anywhere else. 我不会问这个问题是否可以在其他地方找到答案。

Solution is simple: you are not overriding equals in your class, common mistake. 解决方案很简单:您不会在班级中压倒平等,这是常见的错误。 Always annotate your methods with @Override so you can avoid this mistake. 始终使用@Override注释方法,以免发生此错误。

Real equals method is taking an Object parameter, and yours has a Job as parameter, change that to Object and then cast it accordingly. 真正的equals方法采用一个Object参数,而您的Job具有一个Job作为参数,将其更改为Object ,然后进行相应的转换。

If you are using IDE I suggest right click -> source -> generate equals and you will see a good example how to do it. 如果您使用的是IDE,我建议right click -> source -> generate equals ,您将看到一个很好的示例。

You have to override your methods like this 您必须像这样重写您的方法

@Override
public boolean equals(Object a) {
    if(!(a instanceof Job))
        throw new IllegalArgumentException();
    Job job =(Job)a;
    if(this.jobId == job.getJobId() || this.owner.equals(job.getOwner())) {
        return true;
    }
    else
        System.out.println("nomatch");
    return false;
}

See also Why do I need to override the equals and hashCode methods in Java? 另请参见为什么我需要在Java中重写equals和hashCode方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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