0

I'm trying to figure out what the syntax is for calling an object inside a method..

Pseudocode:

    boolean check(Object someObject) {
        return someObject == theOtherObject;
    }

   public static void main(String args[]) {
    someClass one = new someClass();
    someClass two = new someClass();
    one.check(two);
}

So the check method is supposed to check whether the two objects are equal, but how would I specify the other object (theOtherObject should be one)?

Thanks in advance!

Tom
  • 279
  • 1
  • 11

3 Answers3

2

One word answer: this

boolean check(Object someObject) {
    return someObject == this;
}

which will test object identity only. You should override equals and use that.

if (one.equals(two)) {
    // ...
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can have the boolean check(Object o) method inside SomeClass and check

boolean check(Object o) {
    this == (SomeClass) o;
}

This would work only if both reference variables are pointing to same object. Moreover the right way to check if two objects are meaningfully equal would be to use the inherited equals and hashCode method.

Override equals and hashCode method.

Why do I need to override the equals and hashCode methods in Java?

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-

subject-q
  • 91
  • 3
  • 19
0

So what you're asking for there is actually already a command in java.lang.Objects class to compare to objects.

    one.equals(two)

the comparison this does is called a shallow comparison. So if that's what you're looking to do then this would work. For reference, the definitions of shallow comparison defined by geeksforgeeks.org is


Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is also known as a shallow comparison.


if you're looking to do a more complicated comparison you're the best bet would be to actually override the equals command in the one class file


this article would be a good place to start to learn more about this topic. https://www.geeksforgeeks.org/equals-hashcode-methods-java/