equality by value and equality by refernce with linked list

80 Views Asked by At

it seems very difficult to get a proper source of information about Squeak. I have a few basic questions about it:

  1. does '=' check for equality by refrence?

  2. does '==' check for equality of values?

  3. collection - linked list - if I do something like:

    list := LinkedList new.
    
    element := list first.
    

does it mean that element and 'list first' are both references to the same place in memory (the first place in thr linked list?)

  1. why do I need to override the operator = for linked list? and how do I do it?
1

There are 1 best solutions below

0
On BEST ANSWER

By default == is equality by reference. In Object = is defined as

= anObject

   ^ self == anObject

But other classes usually override it. For example in Character = is defined as

= aCharacter 

   ^ self == aCharacter or:[
      aCharacter isCharacter and: [
         self asciiValue = aCharacter asciiValue]]

You can get all implementors of = by executing #= implementors.

In your case element and list first are referencing the same object. This is because first is implemented as

first
   ^ self at: 1

And at returns the element on position 1. But if first would be implemented as

first
   ^ (self at: 1) copy

then it would return a copy of an element (or if you use element := list first copy) and then they will return false when compared with ==, but if = is implemented in a smart way it should return true in most cases.

Also be sure that you want to use LinkedList because in which is a fork of it is used mostly for process scheduling and I think that there was a discussion that LinkedList is more of a utility collection. The most used collection with random access features is OrderedCollection