简体   繁体   中英

Compare two objects of the same type in Java

I have a class ObjectX, and two objects of that same class objectX1, and objectX2.

I also have a method that checks which of two objects of that class is the biggest. Each object of the class consists in a large number stored in an arrayList.

Here's the method declaration:

public ObjectX bigger(ObjectX objectX2);

This method is working just fine, it takes another object besides the one from the class itself, and returns which one is the biggest.

My problem though is when i try to call that method inside an if statement, like this:

public static void main(String[] args) {

if((this.bigger(object2)) == this)
    System.out.println("First is bigger!");
else if((this.bigger(object2)) == object2)
    System.out.println("Second is bigger!");
else
    System.out.println("The objects are equal!");

}

The if statement does not check as it was supposed to. How can i solve this ?

There is a number of issues with your attempt.

[ edit - thanks Tim Biegeleisen for spotting this]

Firstly, you reference this in a static context, whereas a class-scoped context cannot know of a specific instance on its own.

Secondly, == is used to compare object references . You should use equals instead.

But in this case, it might not work, depending on your implementation of method bigger .

What I strongly recommend is to implement Comparable<MyObject> instead.

Replace MyObject with either the type of the objects in question, or some interface for all objects you with to compare.

The compareTo(T o) method can the be implemented with the logic in your bigger method, and more!

By contract, it should return:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object

See API here .

You cannot use this in a static method like the main method. You can only use it in an instance method.

使您的对象类实现Comparable并覆盖compareTo方法,这样您就可以定义评估任何类型的对象较大的条件。

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