简体   繁体   中英

Can't auto-generate an equals method with eclipse

I'm using eclipse to write my Java programs now, but I need to override the equals method so it will take the actual data and not the name or id. When I try to auto-generate it the way I know, it says I have no non-static variables. I added some in and it still doesn't work. I don't know enough about Java to do it myself, but I know enough that I would most likely understand what you are talking about. (I'm not done with my code, I just started. The integers x and y were just to try to make it work.)

package mainPackage;
import java.util.*;

public class Main extends Creater {
    public static void main(String[] args) {
        int x = 0;
        int y = 0;
        thatInput = Inputs.ask();
        Loops.CreateArray();
    }
}

The message that you have "no non-static variables" is giving you the right hint. Override the hashCode and equals methods only makes sense if there are non-static variables in the class. So if you changed your example to the following, you could implement those methods (or have them auto-generated for you by eclipse):

public class Main extends Creater {
    private int x = 0;
    private int y = 0;

    public static void main(String[] args) {
        // other code
    }

    @Override
    public boolean equals(Object obj) {
        // ... your equals code goes here
    }

    @Override
    public int hashCode() {
        // ... your hashCode, er, code goes here
    }

    // ... other code that does wonderful things with x and y
}

Note how I've moved your x and y variables to be at the class level rather than at the method level where you had them. Please also note that someone who or something that creates is a creator , not a creater , that I wouldn't recommend naming your package mainPackage , and that I wouldn't go importing java.util.* in every class just for the sake of it (if you're using eclipse, just do Ctrl + Shift + O to organise your imports).

Please also see which issues to consider when overriding these methods .

To automatically add equals and hashCode methods:

  1. Menu -> Source -> Generate hashCode() and equals()
  2. Select the fields you want make part of hashCode() and equals()
  3. Click Ok

The rest will be done by eclipse.

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