简体   繁体   中英

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. One part of the lab asks me to declare a static equals method in the interface.

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.

In your design, the only way to access the elements of the Set is to convert it to an Array and use that Array. That is quite inconvenient.

The java.util.Set interface extends Iterable, so you can iterate over it directly. Even using the for-each loop. You could add that to your Set as well.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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