Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

== (equal to operator) and object references 4

Status
Not open for further replies.

1DMF

Programmer
Jan 18, 2005
8,795
0
0
GB
Hi,

I'm a newbie, trying to learn OO via a Java course.

I'm on a section regarding expressions, operators / operands.

It states that if you use the == (equals to) operator with any of the opreands being a reference variable to instances of objects, it will always return false if they both do not contain the reference to the same object instance.

Is this just in java or true of any OO language when using object vars and the == (equals to) operator.

Also I was wondering if it is possible to create a primitave variable type which is equal to the value of the reference of the object instance (it's memory address).

Not sure I've explained that well, but it's like in perl, you can make a standard string scalar variable my $myvar = the memory reference of say a hash or array.

So it is a scalar variable not an object reference type variable.

Is this logic going to cause me problems and should I forget anything I know of other languages?

It's just it seems odd you need to create a variable of a class type if all it is going to do is hold a memory reference, not the actual object, which is all an object referecne is.

how big is an object reference variable if it isn't actually holding the object and its state attributes?

It just seems a bit alien to me to create two vars which are seamingly different (one being an object reference) and the other being a refrence to the object variable which is referencing the object instance...

my example..

Code:
Book myBook = new Book();
Book myBook2 = myBook;

why does myBook2 have to be a class defined reference variable, when it's just holding a memory location to the object referenced by myBook.

Any help undertanding why is appreciated.

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
I cannot speak to the memory allocation stuff. that's beyond my understanding. I can speak to == operators. However, Java and .net are similar enough that this should point you in the right direction. with .net I need to implement the equals operators for my classes. lets define our book class
Code:
class Book
{
   public string Title {get;set;}
   public Person Author {get;set;}
}
here is our first pass at equality
Code:
var book1 = new Book 
   {
      Title = "Book of Foo", 
      Author = new Person() 
   };
var book2 = new Book 
   {
      Title = "Book of Foo", 
      Author = new Person() 
   };
var book3 = book2;
book1 == book2; //false
book1.Equals(book2); //false

var book3 = book2;
book2 == book3; //true
book2.Equals(book3); //true
first I need to override how the Book object calculates equality.
Code:
class Book : IEquatable<Book>
{
   public override Equals(object other)
   {
        if(!Equals(other, null)) return false;
        if(!Equals(other, this)) return true;
        if(other.GetType() != typeof(Book)) return false;
        return Equals(other as Book);
   }

   public Equals(Book other)
   {
        if(!Equals(other, null)) return false;
        if(!Equals(other, this)) return true;
        return Equals(Title, other.Title) && Equals(Author, other.Author);
   }

   //not exactly sure why this i need this, but all the documentation I read about overriding equality say Equals and GetHashCode go together.
   public override int GetHashCode()
   {
       unchecked 
       {
          var hash = Title.GetHashCode();
          return hash ^ 367 + Person.GetHashCode();
       }
   }
}
now our code will be interpreted
Code:
book1 == book2; //false
book1.Equals(book2); //true
now I implement == and != operators
Code:
class Book
{
   public static bool operator == (Book a, Book b)
   {
        return Equals(a, b);
   }

   public static bool operator != (Book a, Book b)
   {
        return !Equals(a, b);
   }
}
and the results
Code:
book1 == book2; //true
book1.Equals(book2); //true
that's my understanding of equatable objects in the .net work. maybe this will shed some light on equality in java. if this looks familiar; it's the basis of object equality for (N)Hibernate entities.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Sorry some of that went way over my head, we haven't started defining classes or methods yet (which they seem to call messages?)

I was just wondering if it was an OO thing or a Java thing.

As Java is anally OO from the ground up, not OO bolted on as with most other OO languages.

This is shown by the fact String is an object of class String not a primitive variable.

So a string is an object made up of chars, though I'm still not sure if its an object made up of primitive data type char or of object class 'char', as their spiel over how word processors work , each character is an object.

Though I undesrand that a char is of data type double as it's unicode which is made up of 16bits and superseeds ASCII which can be stored as a byte.

Boy it's all a lot to take in at first, especially as self study!

They do talk about object 'content' comparison of a String class using the example..
Code:
String limb = "Arm";
String name = "Armstrong";

----------------------------
name.Equals(limb + "strong");
----------------------------
Will return true as that performs String object text comparisons, though I find it odd that you can use the plus (+) operator to concatinate object content , but not equals (==)to do a comparison.

I'm also confused why when definsing a String, seings as it is realy a String object of class String you don't have to use the constructor to create is ...ie.

Code:
String myString = new String();

if it's an object why doesn't it follow the rules of an object and require the operator / constructor to create the String object?





"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
I think String is a bit of a special case. Here is what I think, though you might want to double check.

If I create an instance of Object Car
Code:
Car car1 = new Car();
I can either make another reference to the same car, which is just a pointer to the same memory allocated for car1
Code:
car2 = car1;
in this case, car1 == car2;
or I could make another car, with its own memory and just have the same attributes
Code:
car3 = car1.clone();
so car3.equals(car1) is true but car3 == car1 is false.
Now if I'm correct then making a change to car one (lets say car1.refuel() or something that changes the instance of the car object, then car2 (actually being the same car as car1) will maintain all the same attributes. so
car2==car1 and car2.equals(car1) still, but now car3.equals(car1) is false.

Again, String is a bit of a special case, acting as a primitive in some cases (you can say String myString ="heythisisastring" ) and an Object (String myString = new String(charArray[]) ). in others.

Let me know if that makes sense.

-----------------------------------------
I cannot be bought. Find leasing information at
 
josh, that is much better explanation :)

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
yup many thanks, Ok I have to accept that String is a special case. And I understand the concept of a variable = object, making it the same memory address so altering the state of car1 shows the same state in car2.

though can you code it as you have shown ?
Code:
car2 = car1;
OK I know VB / MS allows non declaration of vars.

But i still find it odd you need to define the second car variable as a reference to an object as if you were going to create an object, when it's just holding an address.

The variable defenitions are the same thought they are not the same.

one is an object the other is just pointing to the address of another object.

so that code in full would be..
Code:
Car car2 = car1;

defining car2 as an object of class Car.

Anyways, why would you do that? why have multiple variables all pointing to the same object instance.

That's dodgy coding isn't it?

Again, String is a bit of a special case, acting as a primitive in some cases (you can say String myString ="heythisisastring" ) and an Object (String myString = new String(charArray[]) ). in others.
is that how you define myString to be an Array?

where by you are now using the 'new' operator and a constructor to create a string, but of a diferent data type (Array).

hmm, seems like the class String certainly is a special animal indeed.

there also seems to be some addtional data types i've not come across yet as it seems you are creating the array specificaly to hold only data of type char (charArray[]), is that right?

So i'm guessing there is an intArray[], StringArray[] etc..

Also why is there a primitive type char if all it is is a double?

I guess it is again a special type identifying it as a unicode char not a double sized numeric.

I appreciate your input, it's alot to get your head round when never having done OO programming before.

Thanks 1DMF












"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Anyways, why would you do that? why have multiple variables all pointing to the same object instance.
normally you wouldn't this is just for academic knowledge. where this does come into play
Code:
class ParkingLot
{
  private List<Car> cars = new List<Car>();

  public void Park(Car car)
  {
     cars.Add(car);
  }

  public Car[] Cars
  {
      get { return cars.ToArray(); }
  }
}
Code:
var car = new Car();
var lot = new ParkingLot();
lot.Park(car);

Assert.AreEqual(car, lot.Cars[0]);
again academic in nature.
ParkingLot is just a wrapper around a collection of cars.
here's the practical part: lot will hold a reference to car via the list, but not the actual car object. therefore car and lot.Cars[0] are the exact same object.

when passing car around I'm not passing a copy of the car object, only a reference to the actual object.


Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
you're right, I should've had
Car car2 = car1;
Looking at the java API might be helpful. According to the String API, a String is returned when you call the constructor and pass a character array. That is a common way to instantiate an object, calling the constructor. String is special because you can also instantiate one by setting it equal to a literal.
To create a String array, the syntax is
String[] stringArray = new String[arraySize];
multidimensional like String()[][] string2D = new String()[d1Size][d2Size];
Strings are final, meaning the value cannot change. So if you have a String and try to change the value of it, a new instance of the String object is created, and a new memory reference.

-----------------------------------------
I cannot be bought. Find leasing information at
 
when passing car around I'm not passing a copy of the car object, only a reference to the actual object.
no problem I get this concept, due to working with PERL so much and hash / array references.

Code:
public void Park(Car car)  {     cars.Add(car);  }

I'm guessing that List is another special class of object and it has predefind methods such as the ADD to add an object to the list.

I got a lot more reading to do before i'll be getting to all that i'm sure. [flip]





"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Strings are final, meaning the value cannot change. So if you have a String and try to change the value of it, a new instance of the String object is created, and a new memory reference.
huh?

So if I did
Code:
String myString = "hello";
and then
Code:
myString = "goodbye"
the old object is removed from memory and a new one is created, is that what you mean?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
strings are immutable. same as the DateTime object in .Net.
once the object is created, it cannot be changed. a Point object is a classic example
Code:
class Point
{
   public Point(int x, int y)
   {
      X = x;
      Y = y;
   }

   public int X {get;private set;}
   public int Y {get;private set;}

   public Point Add(Point p)
   {
       return new Point(X+p.X, Y+p.Y)l
   }
}
once you create an instance of Point you cannot change it, you need a new instance.

what this means for strings
Code:
string s = "";
for(int i=0; i<10;i++)
{
   s += i.ToString();
}
Console.WriteLine(s);
every time s is set equal to the new string it creates another memory allocation. I believe you will end up with 11 objects in memory. Not 1 object updated 10 times.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Seems odd if it's meant to be an object , yet you cannot change its state? If it has no getter / setter state methods? (accessors I believe they call them)

Doesn't sound like an object to me!

So in your example, if you end up will 11 objects, what memory location is 's' referencing and how would you access the other objects?

if the other instances of the objects are not 'released' from memory , sounds like you would run out of memory pretty darn quick, doesn't sound very efficient.






"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
1DMF said:
It states that if you use the == (equals to) operator with any of the opreands being a reference variable to instances of objects, it will always return false if they both do not contain the reference to the same object instance.

Is this just in java or true of any OO language when using object vars and the == (equals to) operator.
No, it's a Java thing I'm afraid (and other Java-like languages). In languages like C++ where you can do operator overloading, you can overload the == operator to do a proper comparison of objects.
 
Seems odd if it's meant to be an object , yet you cannot change its state? If it has no getter / setter state methods? (accessors I believe they call them)
Doesn't sound like an object to me!
immutable objects have there place. they are thread safe as there state cannot change. you can utlize them in a "insert/readonly" context.
So in your example, if you end up will 11 objects, what memory location is 's' referencing and how would you access the other objects?

if the other instances of the objects are not 'released' from memory , sounds like you would run out of memory pretty darn quick, doesn't sound very efficient.
the first part, I don't know. that's beyond my understanding of programming.
as for OOM (out of memory). with .net there is the concept of garbage collection which cleans up object allocation. so this doesn't become an issue is most cases. there are ways of handling string concatenation in .Net. Most notably the StringBuider object.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Guys / Gals

You are diamonds. It's all so much clearer now.

I'm sure I'll be back with more dumbfounded questions and really appreciate the time you have taken to explain things to me.

Have a great weekend! [thumbsup2]



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
1DMF. I appreciate you are learning Java (possibly for work), but with your Perl bias you might want to take a look at Ruby. Many of the features will be familiar from Perl, but it is fairly brutal in its application of OO principles. Everything is an object and there are no primitive types at all, but it has a more relaxed attitude to typing than Java. It might ease you in to a more OO way of thinking before tackling Java?

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Too late steve, the course is paid for and already started!

Plus for the qualification I'm trying to achieve (diploma), it has OO with Java as a 'required' module, you get no choice in the matter!

So far, i've not found it a problem, it's all making sense and I feel confident with my progress, why do I get the feeling you feel different ;-)

Of course I'll have questions and it'll take me a few soreheads before it sinks in, but that's no different than anything you learn from scratch, I didn't go straight for my driving test, did you? I had to take lessons, and it took more than one lesson and two test attempts, before I passed. That doesn't make me a bad driver!

It's interesting that Ruby is more true OO and is something I might look at further down the road. True OO and has a perl like syntax, I like the sound of that.

I find it ironic that the people who developed Java did so on the premise of writing a true OO language from the ground up rather than bolting it onto an existing language like VB or C Objective.

Then broke their own rules and created primitive types, yet SmallTalk was already in existence at the time and is built on everything being objects, so literals are objects and operators are methods.

looks like the Java teamed failed miserably in their goals.

Though the course is not aimed at specifically teaching you Java, it's about Object Orientated programing, they just happened to choose Java as the language to teach the OO concepts.

So Java was not a choice, it's pre-requisite, I'll let them know you think it is a poor choice of language [lol]

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
The vast majority of programming jobs these days are all Java, so learning Java would be a very good thing. I've never used SmallTalk, but I thought it was mostly an academic language rather than a real world language? I don't think I've ever seen a job posting for SmallTalk.

I just started learning Ruby for a project at work, and from what I've heard about it, it sucks. I guess I'll find out once I start learning more about it.
 
Dunno, from what i've seen , it seems to be .NET, but as that allows anylanguage to be JIT compiled, not sure it really matters. It's the OO thing I need to learn first!!!

Good luck with the Ruby :)



"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
I just started learning Ruby for a project at work, and from what I've heard about it, it sucks.
no language sucks. just as no language is the best. each language is designed to solve a different problem.

each has it's strengths and weaknesses. ruby is a dynamic language specifically designed for web development (that's my understanding) to use it for anything else is analogous to driving a nail with a screw driver.

if i was concerned with real-time (like real, real-time: TelCom , air traffic control, nuclear power) execution I wouldn't use java or any .net language as there is enough overhead that it's not true real-time.

I believe erlang is great for parallel processing. something to do with TelCom I believe.

I perl is great for parsing text, especially large amounts of text.
from what i've seen , it seems to be .NET, but as that allows any language to be JIT compiled, not sure it really matters.
this isn't entirely true. each language also requires an compiler. the compiler translates said language to merge module. the MM consists of Intermediate Language assember (IL) and metadata.

There are a number of compilers out there. the big 2 are C# and VB. there is also IronRuby, IronPython, Boo, etc. I believe there are even compilers for legacy languages like FORTRAN, LISP, Haskell... these are not well known and I have only heard them mentioned in readings, but they exist.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top