简体   繁体   English

我如何在比较接口的两种实现类型的通用接口中声明 static equals 方法?

[英]How do i declare a static equals method in a generic interface that compares two types of implementation of the interface?

I am studying java for a class and as part of my lab we have practiced different implementations of a generic Interface that represents the Set ADT.我正在为 class 研究 java,作为我实验室的一部分,我们已经实践了代表 Set ADT 的通用接口的不同实现。 One part of the lab asks me to declare a static equals method in the interface.实验室的一部分要求我在接口中声明一个 static equals 方法。

In my own attempt this is what i have created在我自己的尝试中,这就是我创造的

package lab5;

public interface Set<T> {
    
    public static boolean equals(Set<T> equalSetOne, Set<T> equalSetTwo ) {
        Object[] testArrayOne;
        Object[] testArrayTwo;
        testArrayOne = equalSetOne.toArray();
        testArrayTwo = equalSetTwo.toArray();
        
        
        if((testArrayOne.length != 0) && !(equalSetTwo.isEmpty())) {
            for(int i = 0; i < testArrayOne.length; i++) {
                if(!equalSetTwo.contains(testArrayOne[i])) {
                    return false;
                }
            }
        }
        
        if((testArrayTwo.length != 0) && !(equalSetOne.isEmpty())) {
            for(int i = 0; i < testArrayTwo.length; i++) {
                if(!equalSetOne.contains(testArrayTwo[i])) {
                    return false;
                }
            }
        }
        
        return true;
    }
        
    public boolean add(T newElem);
    public T remove();
    public boolean remove(T removedElem);
    public int getSize();
    public boolean isEmpty();
    public boolean contains(T containElem);
    public void clear();
    public Object[] toArray();
}

I am unsure of how to declare the variables in the equals method so that they work for any Set implemented object. Thank you for any help you can provide.我不确定如何在 equals 方法中声明变量,以便它们适用于任何已实现的 Set object。感谢您提供的任何帮助。

In your design, the only way to access the elements of the Set is to convert it to an Array and use that Array.在您的设计中,访问 Set 元素的唯一方法是将其转换为数组并使用该数组。 That is quite inconvenient.那很不方便。

The java.util.Set interface extends Iterable, so you can iterate over it directly. java.util.Set 接口扩展了 Iterable,因此您可以直接对其进行迭代。 Even using the for-each loop.即使使用 for-each 循环。 You could add that to your Set as well.您也可以将其添加到您的 Set 中。

public interface Set<T> extends Iterable<T> {

  public static boolean equals(Set<T> equalSetOne, Set<T> equalSetTwo ) {
    for (T elementOne: equalSetOne) {
      ...  
    }

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

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