• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

problem about keys of hashtable

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see a book write:

you want objects of your class to be used as keys for a
hashtable (or as elements in any data structure that uses equivalency for searching for�and/or retrieving�an object), then you must override equals()so that two different instances can be considered the same.

but why the code below can compile without wrong?

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would expect that the compliler would allow you to do this since I believe it is up to the programmer to ensure the equals method is overriden. Here is a slight addition to the code I used to test this theory:

<code>
import java.util.*;

public class HashTest{
public static void main(String args[]) {
class Car{ }
Hashtable ht = new Hashtable();
Car c1 = new Car();
Car c2 = new Car();
ht.put(c1,"10");
ht.put(c2,"20");
System.out.println(ht.get(c2));
System.out.println("Equality test of c1.equals(c2): " + c1.equals(c2));
}
}
</code>

When I run this, it the following:
20
Equality test of c1.equals(c2): false
 
blacksmith
Posts: 979
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

It compiles without error, because every
class is a subclass of the Object class
which implements some very important
methods like equals, hashCode, wait,
etc...

So if you don't explicitly override the
equals method in your Car class the
inherited equals method from Object will
be used. This works fine.

Cheers,

Gian Franco
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic