设置实现等于方法总是 returns false

Set Implementation Equals Method Always returns false

我的方法之一在 Java Set class 的实现中不起作用。为什么 equals 总是 return false

public boolean equals(Set<E> s) {   
    if(this.size() == s.size()){
        for(int i = 0; i < size(); i++){
            if(theData[i] == s.get(i)){
                return true;
            }
        }
    }
    return false;
}

我的集合是 Set<Integer>,我比较了一组 (1,2,3,4) 和 (1,2,3,4) 并输出 false

编辑:我所有的集合都按从小到大的顺序排列。

EDIT2:这是我在主驱动程序中处理 equals 的代码

    else if(spaceSplit[0].equals("equal")){
            if(spaceSplit.length == 3){ 
                String fSet = spaceSplit[1];
                String sSet = spaceSplit[2];

                int fSetIndex = 0;
                int sSetIndex = 0;

                for(int i = 0; i < sets.size(); i++){
                    if(((Set<Integer>) sets.get(i)).getName().equals(fSet)){
                        fSetIndex = i;
                    }
                }

                for(int i = 0; i < sets.size(); i++){
                    if(((Set<Integer>) sets.get(i)).getName().equals(sSet)){
                        sSetIndex = i;
                    }
                }

                System.out.println(sets.get(fSetIndex).equals(sets.get(sSetIndex)));

            } else {
                System.out.println("Parameters entered wrong, please try again.");
            }

EDIT3:在我的程序中,我一直在搞乱它,每次我放入一个真实的集合时它都会输出 false。如果我只是组成 2 个不存在的集合并调用 equals 方法,它会输出true。我很困惑。

EDIT4:这是更多设置代码:

import java.util.*;

public class Set<E extends Comparable> {

private String name;
private int size = 0;
private E[] theData;
private static final int INITIAL_CAPACITY = 100;
private int capacity = 0;

public Set() {
    capacity = INITIAL_CAPACITY;
    theData = (E[]) new Integer[capacity];
}

public Set(String name) {
    this.name = name;
    capacity = INITIAL_CAPACITY;
    theData = (E[]) new Integer[capacity];
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

private void reallocate() {
    capacity = 2 * capacity;
}

比较应该是 .equals 而不是 ==。

这样试试:

public boolean equals(Set<E> s) {   
    if(this.size() == s.size()){
        for(int i = 0; i < size(); i++){
           if(!this.get(i).equals(s.get(i))){
              return false;
           }
        }
        return true;
    }
    return false;
}

你的问题是你没有覆盖 equals()

签名不是

public boolean equals(Set<E>) 

public boolean equals(Object) 

这就是为什么当您添加 @Override 注释时会出现编译器错误。您必须使用 Object 作为参数,然后检查 instanceof 和 cast.