1

我需要澄清 Object 的 equal 方法中的 String[] 比较。下面是我的代码快照。当我执行这段代码时,它给出的是真假而不是真假。同样在我的情况下,任务类为每个调用生成唯一的 id。我究竟做错了什么?任何建议将不胜感激。

public class JobTask extends Task {

    String[] args;

    public WFTask(String[] args) {
        this.args = args;
    }
    @Override
    public boolean equals(Object obj) {        
            if (! ( obj instanceof String[] ) ){
            return false;           
            }
            String[]  arguments = (String[] ) obj;
            boolean ret = Arrays.equals(this.args , arguments );
            return ret;
    }
    @Override
    public void execute(TaskExecutionContext context) throws RuntimeException {
            --------------
            --------------
    }
    public static void main(String[] args) {
            String[] arg1 = {"a","b","c"};
            String[] arg2 = {"a","b","c"};
            System.out.println( Arrays.equals(arg1,arg2));
            JobTask t1 = new JobTask(arg1);
            JobTask t2 = new JobTask(arg2);
            System.out.println( t1.equals(t2));
    }
}

public abstract class Task {
    private Object id = GUIDGenerator.generate();
    public Task() {
    }
    Object getId() {
       return id;
    }
    public abstract void execute(TaskExecutionContext context)                  throws RuntimeException;
}
4

3 回答 3

3
@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        JobTask other = (JobTask)obj;
        if (!Arrays.equals(args, other.args))
            return false;
        return true;
    }
于 2013-01-04T10:51:19.207 回答
3

您将能够在调试器、提示、提示中看到这一点,但是

你在测试

System.out.println( t1.equals(t2));

但你写了

    if (! ( obj instanceof String[] ) ){
        return false;           
        }

并且由于 t2 不是 aString[]这将返回 false。我怀疑你打算写

    if (!(obj instanceof JobTask))
        return false;           

    JobTask other= (JobTask ) obj;
    return Arrays.equals(this.args , other.args);
于 2013-01-04T10:52:32.487 回答
1

您的equals方法接收 a JobTask,而不是 a String[]。您需要像这样重写它,例如:

@Override
public boolean equals(Object obj) {
    if (! ( obj instanceof JobTask ) ){
        return false;
    }
    String[]  arguments = ((JobTask) obj).args;
    boolean ret = Arrays.equals(this.args , arguments );
    return ret;
}
于 2013-01-04T10:52:45.953 回答