Well, one (==) is the equality operator used to compare two values placed on opposite sides of the operator, and the other ( equals() ) is a method that can be used by some Java classes to determine whether one member of the class is equal to another.
Learning Java using Eclipse on OpenSUSE 11.2
Linux user#: 501795
Greg Brannon wrote:Well, one (==) is the equality operator used to compare two values placed on opposite sides of the operator, and the other ( equals() ) is a method that can be used by some Java classes to determine whether one member of the class is equal to another.
Abhishek Bose wrote:In program 1 are i1 and i2 referring to diff object and in prog 2 are they referring to the same object.??
It looks puzzling, because the two pieces of code seem to be exactly the same, except the value (1000 vs. 10).
If you assign an int value, such as 1000 or 10 to an Integer object, then the value is autoboxed. The compiler does this:
The valueOf() method does some special things: it has a cache of Integer objects for all values between -128 and 127. So, if the value is in that range, it will return a pre-existing Integer object. Otherwise it will create a new Integer object with the specified value.
In the first case, the value 1000 is outside the range, so i1 and i2 will both refer to separate, new Integer objects.
In the second case, the value 10 is inside the range, so i3 and i4 will both refer to the pre-existing Integer object with the value 10 from the cache.
This mechanism has been discussed on the forums before, so if you search in the forums you'll find other discussions of how this works.
I read that if a.equals(b) is true then a.hashcode==b.hashcode()
but if a.hashcode==b.hashcode() is true then it is not necessary that a.equals(b) is also true.... i m not able to understand this logic....
Let us start with some things you probably know and work up from there.
You can instantiate a class -- like Integer -- multiple times. Each instance is called an "object", which unfortunately is a term occasionally used loosely. Each object has characteristics that can be different from or the same as other instances of that class, so different objects of class Integer can have the same or different int values.
Any object instance may be referred to by any number of variables. If you had a class "Automobile", created an instance and loaded it up with whatever attributes it had - year, make, model, color, etc. - you could then have 1, 2, or more variables that all referred to that particular automobile. If you changed one of the attributes - fullOfGas, say - then all the variables that referred to that object would, when they obtained the value of the attribute, get the updated value, because they all refer to that object.
For all of those variables, car1 to carN, the expression (carX == carY) would return true, because they all refer to the same object. That's what == does: tells you whether the two variables refer to the same object.
The equals method, defined on Object so it exists for all java classes, is intended to tell you whether two objects have the same value(s). This is obviously different for different classes; what constitutes equality for your Automobile class will depend on your use of it. The definition of equals dictates that, if you call it on two references to the same object, it had better return true; other than that it's up to you and your classes.
Now, Integer is a java class which instances are immutable; that means that, after you create one, you cannot change its value. Therefore the java compiler/runtime/whatever can feel free to reuse an instance of the class if it can tell, at compile time, that the second use has the same value as some other Integer object you've created. Since the value cannot change and therefore you cannot have a situation where your code changes one object's value and not the other.
I think it best if the programmer does not pay a lot of attention to when it is the compiler and runtime does this little bit of optimization, i.e., the re-using of an object instance that cannot change. It isn't a good thing to depend on, if for no other reason than that the rules are not easy to remember and follow. They're obscure, and it isn't a particularly useful thing for your application.
Use == when what you want to know is whether two variables refer to the same object. Use equals() when you want to know whether two objects have the same value. Don't worry about whether the compiler decided it could use the same object reference instead of a new object in any given case.
It's very simple: If you want to be able to check if two objects of a class you wrote yourself are logically equal, you'd override the equals() method in your class.
Suppose you have a simple Person class, which holds the name and birth date of a person. If you want to check if two Person objects have the same content, you have to override the equals() method to check that the name and birth date of the two Person objects are the same.
Joined: May 29, 2005
Let's go back to the Automobile example. You have some application that benefits from having a class for Automobiles, and you instantiate the class for each Automobile in your application.
It seems reasonable that, at some point, you want to know if two of your automobiles are the same. Exactly what this means depends on your application. You might want to know if they're the same make, model, color, etc.; you might want to know if they're exactly the same vehicle. The point is that what it means depends on how you're using them.
So Java cannot help you decide when two automobiles are "equal"; you have to do that. However, Java does have utility classes that will use the common method equals() to figure that out.
So you can implement equals() in the way that suits your application, and the utility classes will use it. At that point, you will likely also have to implement hashcode, since, for equals to work, hashcode has to return the same value for two 'equal' objects.
Abhishek Bose wrote:
1.Why it is necessary to override hashcode, and what if we do not override equals()..
2.also explain these in context of hashtable...!!!
Let's extend the Automobile example a bit.
You're the owner of a rental car company, with 4 rental-car lots. One is near the airport, one is near the train station, one near the ferry, and one near the bus-depot. You have a bunch of cars, and you need to decide which lot each car should go into.
You could allocate them by color: all the red cars at the airport, the blue ones at the train station, etc. Assuming an even distribution of colours, you'd have about the same number of cars at each lot. But your customers might complain: they want a red car, but all they find at the bus-depot is the gold ones.
You could allocate them by make ... BMW at the airport, Ford at the train-station, etc. Again, this might evenly distribute the number of cars into the 4 lots, but customer choice is again limited.
You could allocate them by model: compact, convertible, truck, SUV ... with the same problem.
So instead, you decide to create a hash function ... the output of which will determine the lot of each car:
Color: Red=0, Blue=1, Green=2, Gold=3
Make: BMW=0, Toyota=1, Ford=2, Chevy=3
Model: Compact=0, Convertible=1, Truck=2, SUV=3
Lot # = (Color + Make + Model) % 4
4 colours x 4 makes x 4 models = 64 varieties, with 16 varieties in each lot.
A customer at the airport (lot #0) could find a red compact BMW, or a blue Ford convertible, or a gold Chevy truck, etc. If they are looking for a particular model of car (convertible) they should find 4 kinds: Red-Chevy, Blue-Ford, Green-Toyota, Gold-BMW.
Here, the simple hashing function distributed the cars into four different lots. If 1000 new BMW's arrived, they all wouldn't end up in the same lot, they would be distributed roughly equally into the 4 lots. This is one of the properties we look for in a hashing function - it should produce an even distribution of values, even if the input is highly correlated (all BMW's, ... or all convertibles, ... or all blue).
Searching. A hash function should make it easier to find an item. Let's say one of our rental cars was involved in an accident. The police don't know exactly which one, but know it was a green Chevy convertible. Which lot to we search in? Green=2, Chevy=3, Convertible=1, so the lot # is 2 ... so the police should look for the car in the ferry lot. As opposed to looking at all cars, the search gets narrowed down to 1/4 of the entire set.
Our hashing function takes make, model, and colour of an Automobile and turns it into a lot #. Our hash table is the rental car lots; cars with the same hashcode go into and will be found the same place. Can two cars have the same hashcode? Of course! Will two red cars have the same hashcode? Not usually. Will two cars with the same colour, make, and model have the same hashcode? Yes. Will two cars with the same hashcode have the same colour, make, and model? Not likely.
A customer owns a gold, BMW convertible at home. They fly into our city, and want to rent the same kind of car as they have at home. Fortunately, gold-BMW-convertible hashes to 0, which is the airport lot, so they can find that kind of car at the airport.
If we don't override the hashcode(), a default hashcode is provided ... the object's memory location. This is not in anyway related to our car's make, model, and colour. Which lot would it go into? Any of them! How would we find it? We'd have to search through every lot! By providing a hashcode that relates to the search criteria, we can narrow down our search.
The hashcode is not used to test for equality. The equals() function is used for that. Using the hashcode would not speed things up, and would likely slow things down. To test if two Automobiles are equal, we just check if they are both gold, both BMW's, and both convertibles. If we added the hashcode into the mix at the start, we'd have to get the first car's make, model and colour, do some math, get the second car's make, model and colour, do some math, and if they are the same, then we'd check if they are the same make, model and colour. We've done more work! But, it the objects have been segregated into different lots, a search for a particular object can be much, much faster if we just look in the appropriate lot.
m sam wrote:a == b (Compares references, not values)
a.equals(b) (Compares values for equality)
In program 1 are i1 and i2 referring to diff object and in prog 2 are they referring to the same object.??
in case of primary datatypes like int of float a==b works for their values
and a.equals(b) can only be used for objects not primary data types
== operator looks for values stored in the reference ... so
in case of primary data types, they store the bit values themselves ... hence the value is matched directly
in case of object references, they store some link (i do not know which typed of link, because there isn't anything like a pointer in java, anyways) to the actual value mapped to the reference variable
a.equals(b) matches that mapped value, that i just described above ... hence it can not work with primary data types