0

So, let me show the code first.

public class Class1 {
    private static class Class2 {
    String name;
    Object value;
    EntryNode next;

    }

} 

So, as you guess, I am working on linkedlists. So, for a given value as a parameter in a function;

public Object put(String name, Object value) {
    ...
    ...
    if (head.value == value) {
    }
}

So, in particular, can we use this equality symbol '==' for Object class? In general, except Strings, can we use '==' in any class? If it was string, then no. If it was integer, then definitely yes. But now, how can you compare?

luk2302
  • 55,258
  • 23
  • 97
  • 137
ihatec
  • 57
  • 6
  • 3
    Other way around. You should use `equals()` for all classes, not just strings. `==` is a special case. – markspace Apr 12 '22 at 15:40
  • Possibly related: [What's the difference between ".equals" and "=="?](https://stackoverflow.com/q/1643067), [Java: Integer equals vs. ==](https://stackoverflow.com/q/3637936) – Pshemo Apr 12 '22 at 15:44
  • _"If it was integer, then definitely yes."_ definitely not, try it with 128 or higher, or -129 or lower. – Mark Rotteveel Apr 12 '22 at 15:45
  • @MarkRotteveel Oh why? Due to overflow I guess? – ihatec Apr 12 '22 at 16:05
  • @ihatec: No, not overflow. `==` just does the wrong thing, for similar reasons to strings. It's pretty much always the wrong thing to use. – Louis Wasserman Apr 12 '22 at 16:33
  • @ihatec auto-boxing and `Integer.valueOf()` uses a cache of values for integers in the range -128 - 127, outside of that it returns a new value, so two `Integer` values with value 128 are not necessarily `==`, but they are `.equals(..)`. – Mark Rotteveel Apr 12 '22 at 18:08

1 Answers1

3

== with tell you if the right and left hand sides refer to exactly the same instance. This will tend to be give you an unexpected answer for value types such as String, Integer, List, BigInteger, Map, etc. You should almost always use equals, except for primitive types.

If you want to handle null without throwing a NullPointerException, then java.util.Objects.equals (note the plural) can handle that for you.

Project Valhalla may extend the concept of primitives to user defined types in future version of Java.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305