0
Calendar calendar = new GregorianCalendar(2015, 2, 1);
Calendar calendar1 = calendar;
Calendar calendar2 = (Calendar)calendar.clone();
System.out.println("calendar == calendar1 is " + (calendar == calendar1));
System.out.println("calendar == calendar2 is " + (calendar == calendar2));
System.out.println("calendar.equals(calendar2) is " + calendar.equals(calendar2));

displays:

calendar == calendar1 --------------> gives you "true"

calendar == calendar2 --------------> gives you "false"

calendar.equals(calendar2) ---------> gives you "true"

My Question:

When you set two objects equal to each other using "==", are you trying to find whether their memory address are equal to each other? I apologize for the confusion. Perhaps I am not understanding what is being compared and equal here? Thank you so much for all your help.

gordon sung
  • 605
  • 2
  • 8
  • 27
  • *When you set two objects equal to each other using "==", are you trying to find whether their memory address are equal to each other?* Yes. Hence *reference* equality. – Elliott Frisch Mar 16 '16 at 00:17
  • Oh ok! So does that mean when you create a clone of an object, that clone occupies a different memory address? Thank you so very much for your response and answer – gordon sung Mar 16 '16 at 00:18
  • Yes. The `clone` is an independent reference. – Elliott Frisch Mar 16 '16 at 00:18
  • ah I see @ Elliott Frisch Thank you so very much!! I wish I can give you a check/credits but my account does not allow me to. I apologize but thank you so very much! – gordon sung Mar 16 '16 at 00:20
  • 1
    @MikeCAT Where are strings being compared? Read the question – OneCricketeer Mar 16 '16 at 00:23

2 Answers2

2

"==" does not mean "set to" at all - it's completely independent of "=".

"==" means different things depending on what it's used on. For objects, it compares the memory location - equivalently, it calls Object's implementation of .equals(). As "=" assigns a reference, it will make the memory location the same, so "==" will return true. ".clone" creates a copy of an object in a new memory location, so "==" will return false.

When you use .equals(), it's up to the dynamic type of the object you're calling it on to determine the implementation. For Calendar, it checks the values in the intuitive way. There's nothing to stop you form having .equals() for some class you write flip a coin to determine the result, though.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39
1

There is a difference between == and .equals. You can read this post, there is a better answer that I could give you

Community
  • 1
  • 1
Sylvain GIROD
  • 836
  • 1
  • 11
  • 23