简体   繁体   中英

Java generic interface extends Comparable

I want to create a class lets say Employee that implements the generic interface Comparable and overrides the methods equals, hashCode, and toString...How would I be able to do it ?

would this be ok

interface MinMax<T extends Comparable<T>> {

T equals();
T hashCode();
T toString();

}

and

class Employee<T extends Comparable<T>> implements MinMax<T> {

 public T equals(){

  }

  public T hashCode(){

  }

  public T toString(){

  }



  }

There are two parts to the question.

Part 1: Override equals, hashCode and toString.

Simply redefine those methods in you new class with your new implementation.

class Employee {

    //fields and other methods

    public boolean equals(Object other) {
        //new implementation here
    }
    public int hashCode() {
        //make sure two equal objects produce the same hashCode
    }
    public String toString() {
        //return whatever you want here
    }
}

Part 2: Implement the Comparable interface.

I assume you wish to compare to other employees. Declare that it implements Comparable, and implement the compareTo method described by the interface.

public Employee implements Comparable<Employee> {

    //fields and methods

    public int compareTo(Employee e) {
        //new implementation. Should probably be consistent with equals.
    }
}

A class may implement as many interfaces you wish, there's no need to "group" them as well:

class Employee implements Comparable, MinMax{ ... }

You have to provide interface method implementations anyway.

For this you don't need to create your own separate interface.

Equals, hashCode and toString are methods of the object class which your new class will automatically be a subclass of therefore it will have access to these methods without you having to do anything. To override the methods simply create methods of the same name in your new class with what you want the methods to do.

Comparable is a generic interface so where you have the letter T you need to replace it with the class that you want. As you probably want to compare a member of the class with another member of the same class you will replace it with Employee. Your class itself does not need to be generic even though it is implementing a generic interface so there should not be any 'T's in your code

The word 'extends' is for when you want to create a class which is a subclass of another class. Or when you want the class which goes in a generic interface to be a subclass of a certain class. You don't need to do this for your class so the word extends is not needed anywhere.

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