Thursday, May 22, 2008

kalavathi guna

System.Collections Namespace

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.
Classes
Class Description
[Public class] ArrayList Implements the IList interface using an array whose size is dynamically increased as required.
[Public class] BitArray Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
[Public class] CaseInsensitiveComparer Compares two objects for equivalence, ignoring the case of strings.
[Public class] CaseInsensitiveHashCodeProvider Obsolete. Supplies a hash code for an object, using a hashing algorithm that ignores the case of strings.
[Public class] CollectionBase Provides the abstract base class for a strongly typed collection.
[Public class] Comparer Compares two objects for equivalence, where string comparisons are case-sensitive.
[Public class] DictionaryBase Provides the abstract base class for a strongly typed collection of key/value pairs.
[Public class] Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key.
[Public class] Queue Represents a first-in, first-out collection of objects.
[Public class] ReadOnlyCollectionBase Provides the abstract base class for a strongly typed non-generic read-only collection.
[Public class] SortedList Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.
[Public class] Stack Represents a simple last-in-first-out (LIFO) non-generic collection of objects.
Structures
Structure Description
[Public structure] DictionaryEntry Defines a dictionary key/value pair that can be set or retrieved.
Interfaces
Interface Description
[Public interface] ICollection Defines size, enumerators, and synchronization methods for all nongeneric collections.
[Public interface] IComparer Exposes a method that compares two objects.
[Public interface] IDictionary Represents a nongeneric collection of key/value pairs.
[Public interface] IDictionaryEnumerator Enumerates the elements of a nongeneric dictionary.
[Public interface] IEnumerable Exposes the enumerator, which supports a simple iteration over a non-generic collection.
[Public interface] IEnumerator Supports a simple iteration over a nongeneric collection.
[Public interface] IEqualityComparer Defines methods to support the comparison of objects for equality.
[Public interface] IHashCodeProvider Obsolete. Supplies a hash code for an object, using a custom hash function.
[Public interface] IList Represents a non-generic collection of objects that can be individually accessed by

kalavathi guna

Hashtable Class

Represents a collection of key/value pairs that are organized based on the hash code of the key.

Namespace: System.Collections
Assembly: mscorlib (in mscorlib.dll)
Syntax
Visual Basic (Declaration)

_
_
Public Class Hashtable _
Implements IDictionary, ICollection, IEnumerable, ISerializable, _
IDeserializationCallback, ICloneable

Visual Basic (Usage)

Dim instance As Hashtable

C#

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class Hashtable : IDictionary, ICollection,
IEnumerable, ISerializable, IDeserializationCallback, ICloneable

Visual C++

[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class Hashtable : IDictionary,
ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

J#

/** @attribute SerializableAttribute */
/** @attribute ComVisibleAttribute(true) */
public class Hashtable implements IDictionary,
ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

JScript

public class Hashtable implements IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

Remarks

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be nullNothingnullptra null reference (Nothing in Visual Basic), but a value can be.

The objects used as keys by a Hashtable are required to override the Object..::.GetHashCode method (or the IHashCodeProvider interface) and the Object..::.Equals method (or the IComparer interface). The implementation of both methods and interfaces must handle case sensitivity the same way; otherwise, the Hashtable might behave incorrectly. For example, when creating a Hashtable, you must use the CaseInsensitiveHashCodeProvider class (or any case-insensitive IHashCodeProvider implementation) with the CaseInsensitiveComparer class (or any case-insensitive IComparer implementation).

Furthermore, these methods must produce the same results when called with the same parameters while the key exists in the Hashtable. An alternative is to use a Hashtable constructor with an IEqualityComparer parameter. If key equality were simply reference equality, the inherited implementation of Object..::.GetHashCode and Object..::.Equals would suffice.

Key objects must be immutable as long as they are used as keys in the Hashtable.

When an element is added to the Hashtable, the element is placed into a bucket based on the hash code of the key. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, thus substantially reducing the number of key comparisons required to find an element.

The load factor of a Hashtable determines the maximum ratio of elements to buckets. Smaller load factors cause faster average lookup times at the cost of increased memory consumption. The default load factor of 1.0 generally provides the best balance between speed and size. A different load factor can also be specified when the Hashtable is created.

As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.

Each key object in the Hashtable must provide its own hash function, which can be accessed by calling GetHash. However, any object implementing IHashCodeProvider can be passed to a Hashtable constructor, and that hash function is used for all objects in the table.

The capacity of a Hashtable is the number of elements the Hashtable can hold. As elements are added to a Hashtable, the capacity is automatically increased as required through reallocation.
vb# c#

The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the Hashtable is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:
C#
Copy Code

foreach (DictionaryEntry de in myHashtable) {...}

Visual Basic
Copy Code

For Each de as DictionaryEntry In myHashtable
...
Next de

vb# c#

The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Because serializing and deserializing an enumerator for a Hashtable can cause the elements to become reordered, it is not possible to continue enumeration without calling the Reset method.
[Note] Note:

Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.
Examples

The following example shows how to create, initialize and perform various functions to a Hashtable and how to print out its keys and values.
Visual Basic
Copy Code

Imports System
Imports System.Collections

Module Example

Sub Main()

' Create a new hash table.
'
Dim openWith As New Hashtable()

' Add some elements to the hash table. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is
' already in the hash table.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

' The Item property is the default property, so you
' can omit its name when accessing elements.
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"

' ContainsKey can be used to test keys before inserting
' them.
If Not openWith.ContainsKey("ht") Then
openWith.Add("ht", "hypertrm.exe")
Console.WriteLine("Value added for key = ""ht"": {0}", _
openWith("ht"))
End If

' When you use foreach to enumerate hash table elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each de As DictionaryEntry In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
de.Key, de.Value)
Next de

' To get the values alone, use the Values property.
Dim valueColl As ICollection = openWith.Values

' The elements of the ValueCollection are strongly typed
' with the type that was specified for hash table values.
Console.WriteLine()
For Each s As String In valueColl
Console.WriteLine("Value = {0}", s)
Next s

' To get the keys alone, use the Keys property.
Dim keyColl As ICollection = openWith.Keys

' The elements of the KeyCollection are strongly typed
' with the type that was specified for hash table keys.
Console.WriteLine()
For Each s As String In keyColl
Console.WriteLine("Key = {0}", s)
Next s

' Use the Remove method to remove a key/value pair.
Console.WriteLine(vbLf + "Remove(""doc"")")
openWith.Remove("doc")

If Not openWith.ContainsKey("doc") Then
Console.WriteLine("Key ""doc"" is not found.")
End If

End Sub

End Module

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Value added for key = "ht": hypertrm.exe
'
'Key = dib, Value = paint.exe
'Key = txt, Value = notepad.exe
'Key = ht, Value = hypertrm.exe
'Key = bmp, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'
'Value = paint.exe
'Value = notepad.exe
'Value = hypertrm.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'
'Key = dib
'Key = txt
'Key = ht
'Key = bmp
'Key = rtf
'Key = doc
'
'Remove("doc")
'Key "doc" is not found.

C#
Copy Code

using System;
using System.Collections;

class Example
{
public static void Main()
{
// Create a new hash table.
//
Hashtable openWith = new Hashtable();

// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the hash table.
try
{
openWith.Add("txt", "winword.exe");
}
catch
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// The Item property is the default property, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

// The default Item property can be used to change the value
// associated with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

// If a key does not exist, setting the default Item property
// for that key adds a new key/value pair.
openWith["doc"] = "winword.exe";

// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
}

// When you use foreach to enumerate hash table elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( DictionaryEntry de in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}

// To get the values alone, use the Values property.
ICollection valueColl = openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for hash table values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
ICollection keyColl = openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for hash table keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}

// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Value added for key = "ht": hypertrm.exe

Key = dib, Value = paint.exe
Key = txt, Value = notepad.exe
Key = ht, Value = hypertrm.exe
Key = bmp, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe

Value = paint.exe
Value = notepad.exe
Value = hypertrm.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe

Key = dib
Key = txt
Key = ht
Key = bmp
Key = rtf
Key = doc

Remove("doc")
Key "doc" is not found.
*/

Inheritance Hierarchy
System..::.Object
System.Collections..::.Hashtable
System.Configuration..::.SettingsAttributeDictionary
System.Configuration..::.SettingsContext
System.Data..::.PropertyCollection
System.Printing.IndexedProperties..::.PrintPropertyDictionary
Thread Safety

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized method, provided that there are no threads reading the Hashtable object.

Enumerating through a collection is intrinsically not a thread safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Platforms

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information
.NET Framework
Supported in: 3.5, 3.0 SP1, 3.0, 2.0 SP1, 2.0, 1.1, 1.0
.NET Compact Framework
Supported in: 3.5, 2.0, 1.0
XNA Framework
Supported in: 1.0
See Also
Reference
Hashtable Members
System.Collections Namespace
IDictionary
IHashCodeProvider
Object..::.GetHashCode
Object..::.Equals
DictionaryEntry
System.Collections.Generic..::.Dictionary<(Of <(TKey, TValue>)>)
IEqualityComparer
Tags What's this?: Add a tag Add Cancel
Flag as ContentBug
Community Content What is Community Content?
Add new content
Hash Table sample using PowerShell Thomas Lee | Edit | Show History
Please Wait Please Wait

# Get-Hashtable.ps1

# MSDN sample - recoded with PowerShell

# thomas lee - tfl@psp.co.uk

# create new hash table
$openWith = @{}


# Add some elements to the hash table. There are no


#duplicate keys, but some of the values are duplicates.



$openWith.Add("txt", "notepad.exe")
$openWith.Add("dib", "paint.exe"


# Add in a powershell way!
$openwith += @{"bmp"="paint.exe"


# or
$wordpad = "wordpad.exe"
$openwith += @{"rtf"=$word


# Display the Hash table
"The Hash Table so far"
$openwith


# The Add method throws an exception if the new key is
# already in the hash table.



#first catch exception
trap [Exception] {
"***"
write-host "*** An element with Key = `"txt`" already exists."
"***"
continue
}


# now the offending line.
"";"Trying to add an entry with an existing key"
$openWith.Add("txt", "winword.exe");
"Continuing";""


# The Item property is the default property, so you
# can omit its name when accessing elements
# A non-existing key comes up empty
"For key = `"rtf`", value = {0}." -f $openWith["rtf"]


# The default Item property can be used to change the value
# associated with a key.


# add an entry for RTF
$openWith["rtf"] = "winword.exe";
"For key = `"rtf`", value = {0}." -f $openWith["rtf"]


# If a key does not exist, setting the default Item property
# for that key adds a new key/value pair.
$openWith["doc"] = "winword.exe"


# Note Progress with this hashtable
"";"The Hash Table so far:"
$openwith
""


# The ContainsKey method can be used to test keys before inserting them.
# test the "ht" key before adding it into the hashtable
if (!$openWith.ContainsKey("ht")) {
$openWith.Add("ht", "hypertrm.exe")
"Value added for key = `"ht`": {0}" -f $openWith["ht"]
}


"{0} elements in the hash table as follows:" -f $openwith.count
$openwith





# To get the values alone, use the Values property.
$valueColl = $openWith.Values


# To get the values alone, use the Values property.
$valueColl = $openWith.Values


# The elements of the ValueCollection are strongly typed
# with the type that was specified for hash table values.
"";"Value Entries:"
foreach( $s in $valueColl ) {
"Value = {0}" -f $s
}


# To get the keys alone, use the Keys property.
$keyColl = $openWith.Keys


# The elements of the KeyCollection are strongly typed
# with the type that was specified for hash table keys.
"";"Key Entries"
foreach( $s in $keyColl ){
"Key = {0}" -f $s
}


# Use the Remove method to remove a key/value pair.
"`nRemoving(`"doc`")"
$openWith.Remove("doc")


# See if it's tjhere
if (!$openWith.ContainsKey("doc")) {
"Key `"doc`" is not found."
}

kalavathi guna

Introduction

The Java super class java.lang.Object has two very important methods defined in it. They are -

* public boolean equals(Object obj)
* public int hashCode()

These methods prove very important when user classes are confronted with other Java classes, when objects of such classes are added to collections etc. These two methods have become part of Sun Certified Java Programmer 1.4 exam (SCJP 1.4) objectives. This article intends to provide the necessary information about these two methods that would help the SCJP 1.4 exam aspirants. Moreover, this article hopes to help you understand the mechanism and general contracts of these two methods; irrespective of whether you are interested in taking the SCJP 1.4 exam or not. This article should help you while implementing these two methods in your own classes.

public boolean equals(Object obj)

This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison.

This is what the JDK 1.4 API documentation says about the equals method of Object class-

Indicates whether some other object is "equal to" this one.

* The equals method implements an equivalence relation: It is reflexive: for any reference value x, x.equals(x) should return true.
* It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
* It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
* It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
* For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

The contract of the equals method precisely states what it requires. Once you understand it completely, implementation becomes relatively easy, moreover it would be correct. Let's understand what each of this really means.

1. Reflexive - It simply means that the object must be equal to itself, which it would be at any given instance; unless you intentionally override the equals method to behave otherwise.
2. Symmetric - It means that if object of one class is equal to another class object, the other class object must be equal to this class object. In other words, one object can not unilaterally decide whether it is equal to another object; two objects, and consequently the classes to which they belong, must bilaterally decide if they are equal or not. They BOTH must agree.
Hence, it is improper and incorrect to have your own class with equals method that has comparison with an object of java.lang.String class, or with any other built-in Java class for that matter. It is very important to understand this requirement properly, because it is quite likely that a naive implementation of equals method may violate this requirement which would result in undesired consequences.
3. Transitive - It means that if the first object is equal to the second object and the second object is equal to the third object; then the first object is equal to the third object. In other words, if two objects agree that they are equal, and follow the symmetry principle, one of them can not decide to have a similar contract with another object of different class. All three must agree and follow symmetry principle for various permutations of these three classes.
Consider this example - A, B and C are three classes. A and B both implement the equals method in such a way that it provides comparison for objects of class A and class B. Now, if author of class B decides to modify its equals method such that it would also provide equality comparison with class C; he would be violating the transitivity principle. Because, no proper equals comparison mechanism would exist for class A and class C objects.
4. Consistent - It means that if two objects are equal, they must remain equal as long as they are not modified. Likewise, if they are not equal, they must remain non-equal as long as they are not modified. The modification may take place in any one of them or in both of them.
5. null comparison - It means that any instantiable class object is not equal to null, hence the equals method must return false if a null is passed to it as an argument. You have to ensure that your implementation of the equals method returns false if a null is passed to it as an argument.
6. Equals & Hash Code relationship - The last note from the API documentation is very important, it states the relationship requirement between these two methods. It simply means that if two objects are equal, then they must have the same hash code, however the opposite is NOT true. This is discussed in details later in this article.

The details about these two methods are interrelated and how they should be overridden correctly is discussed later in this article.

public int hashCode()

This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method.

This is what the JDK 1.4 API documentation says about the hashCode method of Object class-

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

* The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

As compared to the general contract specified by the equals method, the contract specified by the hashCode method is relatively simple and easy to understand. It simply states two important requirements that must be met while implementing the hashCode method. The third point of the contract, in fact is the elaboration of the second point. Let's understand what this contract really means.

1. Consistency during same execution - Firstly, it states that the hash code returned by the hashCode method must be consistently the same for multiple invocations during the same execution of the application as long as the object is not modified to affect the equals method.
2. Hash Code & Equals relationship - The second requirement of the contract is the hashCode counterpart of the requirement specified by the equals method. It simply emphasizes the same relationship - equal objects must produce the same hash code. However, the third point elaborates that unequal objects need not produce distinct hash codes.

After reviewing the general contracts of these two methods, it is clear that the relationship between these two methods can be summed up in the following statement -

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

The rest of the requirements specified in the contracts of these two methods are specific to those methods and are not directly related to the relationship between these two methods. Those specific requirements are discussed earlier. This relationship also enforces that whenever you override the equals method, you must override the hashCode method as well. Failing to comply with this requirement usually results in undetermined, undesired behavior of the class when confronted with Java collection classes or any other Java classes.

Correct Implementation Example

The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes. This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.

1. public class Test
2. {
3. private int num;
4. private String data;
5.
6. public boolean equals(Object obj)
7. {
8. if(this == obj)
9. return true;
10. if((obj == null) || (obj.getClass() != this.getClass()))
11. return false;
12. // object must be Test at this point
13. Test test = (Test)obj;
14. return num == test.num &&
15. (data == test.data || (data != null && data.equals(test.data)));
16. }
17.
18. public int hashCode()
19. {
20. int hash = 7;
21. hash = 31 * hash + num;
22. hash = 31 * hash + (null == data ? 0 : data.hashCode());
23. return hash;
24. }
25.
26. // other methods
27. }


Now, let's examine why this implementation is the correct implementation. The class Test has two member variables - num and data. These two variables define state of the object and they also participate in the equals comparison for the objects of this class. Hence, they should also be involved in calculating the hash codes of this class objects.

Consider the equals method first. We can see that at line 8, the passed object reference is compared with this object itself, this approach usually saves time if both the object references are referring to the same object on the heap and if the equals comparison is expensive. Next, the if condition at line 10 first checks if the argument is null, if not, then (due to the short-circuit nature of the OR || operator) it checks if the argument is of type Test by comparing the classes of the argument and this object. This is done by invoking the getClass() method on both the references. If either of these conditions fails, then false is returned. This is done by the following code -
if((obj == null) || (obj.getClass() != this.getClass())) return false; // prefer
This conditional check should be preferred instead of the conditional check given by -
if(!(obj instanceof Test)) return false; // avoid
This is because, the first condition (code in blue) ensures that it will return false if the argument is a subclass of the class Test. However, in case of the second condition (code in red) it fails. The instanceof operator condition fails to return false if the argument is a subclass of the class Test. Thus, it might violate the symmetry requirement of the contract. The instanceof check is correct only if the class is final, so that no subclass would exist. The first condition will work for both, final and non-final classes. Note that, both these conditions will return false if the argument is null. The instanceof operator returns false if the left hand side (LHS) operand is null, irrespective of the operand on the right hand side (RHS) as specified by JLS 15.20.2. However, the first condition should be preferred for better type checking.

This class implements the equals method in such a way that it provides equals comparison only for the objects of the same class. Note that, this is not mandatory. But, if a class decides to provide equals comparison for other class objects, then the other class (or classes) must also agree to provide the same for this class so as to fulfill the symmetry and reflexivity requirements of the contract. This particular equals method implementation does not violate both these requirements. The lines 14 and 15 actually perform the equality comparison for the data members, and return true if they are equal. Line 15 also ensures that invoking the equals method on String variable data will not result in a NullPointerException.
While implementing the equals method, primitives can be compared directly with an equality operator (==) after performing any necessary conversions (Such as float to Float.floatToIntBits or double to Double.doubleToLongBits). Whereas, object references can be compared by invoking their equals method recursively. You also need to ensure that invoking the equals method on these object references does not result in a NullPointerException.

Here are some useful guidelines for implementing the equals method correctly.

1. Use the equality == operator to check if the argument is the reference to this object, if yes. return true. This saves time when actual comparison is costly.
2. Use the following condition to check that the argument is not null and it is of the correct type, if not then return false.
if((obj == null) || (obj.getClass() != this.getClass())) return false;
Note that, correct type does not mean the same type or class as shown in the example above. It could be any class or interface that one or more classes agree to implement for providing the comparison.
3. Cast the method argument to the correct type. Again, the correct type may not be the same class. Also, since this step is done after the above type-check condition, it will not result in a ClassCastException.
4. Compare significant variables of both, the argument object and this object and check if they are equal. If *all* of them are equal then return true, otherwise return false. Again, as mentioned earlier, while comparing these class members/variables; primitive variables can be compared directly with an equality operator (==) after performing any necessary conversions (Such as float to Float.floatToIntBits or double to Double.doubleToLongBits). Whereas, object references can be compared by invoking their equals method recursively. You also need to ensure that invoking equals method on these object references does not result in a NullPointerException, as shown in the example above (Line 15).
It is neither necessary, nor advisable to include those class members in this comparison which can be calculated from other variables, hence the word "significant variables". This certainly improves the performance of the equals method. Only you can decide which class members are significant and which are not.
5. Do not change the type of the argument of the equals method. It takes a java.lang.Object as an argument, do not use your own class instead. If you do that, you will not be overriding the equals method, but you will be overloading it instead; which would cause problems. It is a very common mistake, and since it does not result in a compile time error, it becomes quite difficult to figure out why the code is not working properly.
6. Review your equals method to verify that it fulfills all the requirements stated by the general contract of the equals method.
7. Lastly, do not forget to override the hashCode method whenever you override the equals method, that's unpardonable. ;)

Now, let's examine the hashCode method of this example. At line 20, a non-zero constant value 7 (arbitrary) is assigned to an int variable hash. Since the class members/variables num and data do participate in the equals method comparison, they should also be involved in the calculation of the hash code. Though, this is not mandatory. You can use subset of the variables that participate in the equals method comparison to improve performance of the hashCode method. Performance of the hashCode method indeed is very important. But, you have to be very careful while selecting the subset. The subset should include those variables which are most likely to have the greatest diversity of the values. Sometimes, using all the variables that participate in the equals method comparison for calculating the hash code makes more sense.
This class uses both the variables for computing the hash code. Lines 21 and 22 calculate the hash code values based on these two variables. Line 22 also ensures that invoking hashCode method on the variable data does not result in a NullPointerException if data is null. This implementation ensures that the general contract of the hashCode method is not violated. This implementation will return consistent hash code values for different invocations and will also ensure that equal objects will have equal hash codes.
While implementing the hashCode method, primitives can be used directly in the calculation of the hash code value after performing any necessary conversions, such as float to Float.floatToIntBits or double to Double.doubleToLongBits. Since return type of the hashCode method is int, long values must to be converted to the integer values. As for hash codes of the object references, they should be calculated by invoking their hashCode method recursively. You also need to ensure that invoking the hashCode method on these object references does not result in a NullPointerException.

Writing a very good implementation of the hashCode method which calculates hash code values such that the distribution is uniform is not a trivial task and may require inputs from mathematicians and theoretical computer scientist. Nevertheless, it is possible to write a decent and correct implementation by following few simple rules.

Here are some useful guidelines for implementing the hashCode method correctly.

1. Store an arbitrary non-zero constant integer value (say 7) in an int variable, called hash.
2. Involve significant variables of your object in the calculation of the hash code, all the variables that are part of equals comparison should be considered for this. Compute an individual hash code int var_code for each variable var as follows -
1. If the variable(var) is byte, char, short or int, then var_code = (int)var;
2. If the variable(var) is long, then var_code = (int)(var ^ (var >>> 32));
3. If the variable(var) is float, then var_code = Float.floatToIntBits(var);
4. If the variable(var) is double, then -
long bits = Double.doubleToLongBits(var);
var_code = (int)(bits ^ (bits >>> 32));
5. If the variable(var) is boolean, then var_code = var ? 1 : 0;
6. If the variable(var) is an object reference, then check if it is null, if yes then var_code = 0; otherwise invoke the hashCode method recursively on this object reference to get the hash code. This can be simplified and given as -
var_code = (null == var ? 0 : var.hashCode());
3. Combine this individual variable hash code var_code in the original hash code hash as follows -
hash = 31 * hash + var_code;
4. Follow these steps for all the significant variables and in the end return the resulting integer hash.
5. Lastly, review your hashCode method and check if it is returning equal hash codes for equal objects. Also, verify that the hash codes returned for the object are consistently the same for multiple invocations during the same execution.

The guidelines provided here for implementing equals and hashCode methods are merely useful as guidelines, these are not absolute laws or rules. Nevertheless, following them while implementing these two methods will certainly give you correct and consistent results.

Summary & Miscellaneous Tips

* Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
* The equals method provides "deep comparison" by checking if two objects are logically equal as opposed to the "shallow comparison" provided by the equality operator ==.
* However, the equals method in java.lang.Object class only provides "shallow comparison", same as provided by the equality operator ==.
* The equals method only takes Java objects as an argument, and not primitives; passing primitives will result in a compile time error.
* Passing objects of different types to the equals method will never result in a compile time error or runtime error.
* For standard Java wrapper classes and for java.lang.String, if the equals argument type (class) is different from the type of the object on which the equals method is invoked, it will return false.
* The class java.lang.StringBuffer does not override the equals method, and hence it inherits the implementation from java.lang.Object class.
* The equals method must not provide equality comparison with any built in Java class, as it would result in the violation of the symmetry requirement stated in the general contract of the equals method.
* If null is passed as an argument to the equals method, it will return false.
* Equal hash codes do not imply that the objects are equal.
* return 1; is a legal implementation of the hashCode method, however it is a very bad implementation. It is legal because it ensures that equal objects will have equal hash codes, it also ensures that the hash code returned will be consistent for multiple invocations during the same execution. Thus, it does not violate the general contract of the hashCode method. It is a bad implementation because it returns same hash code for all the objects. This explanation applies to all implementations of the hashCode method which return same constant integer value for all the objects.
* In standard JDK 1.4, the wrapper classes java.lang.Short, java.lang.Byte, java.lang.Character and java.lang.Integer simply return the value they represent as the hash code by typecasting it to an int.
* Since JDK version 1.3, the class java.lang.String caches its hash code, i.e. it calculates the hash code only once and stores it in an instance variable and returns this value whenever the hashCode method is called. It is legal because java.lang.String represents an immutable string.
* It is incorrect to involve a random number directly while computing the hash code of the class object, as it would not consistently return the same hash code for multiple invocations during the same execution.

Review Questions

The review questions are available separately - here.

Resources

Here is a list of few more resources that might be useful if you are interested in knowing more about these two methods, their implementation and significance.

* Object class - API documentation for the java.lang.Object class. The general contract of these two methods is available here.
* Effective Java - Nice book by Joshua Bloch. Chapter 3 of this book is available online in a pdf format. This chapter deals with all the methods of java.lang.Object class. It also discusses in details the implementation of equals and hashCode methods, correct and incorrect way of overriding them etc. This article is partially based on the information given in this book.
However, this article is an attempt to explain the mechanism and implementation details of these two methods in a simple and compact presentation. It also adds tips and review questions for better understanding.
* JavaWorld Article - This article discusses the methods of java.lang.Object, also explains shortcomings of using the instanceof condition in the equals method.
* Importance of equals and hashCode - This FAQ question discusses the importance of overriding equals and hashCode methods correctly. It also discusses important issues regarding these two methods with respect to Java collection framework.
* Equals & Hash Code Mock Test - If you are interested in taking the mock test based only on equals and hash code.
* Equals and Hash Code Cartoon - A small cartoon strip that I have written, it attempts to illustrate the relationship between the equals and hashCode methods.
* J@Whiz 1.4 - This has very good questions with detailed explanation based on equals - hashCode and other SCJP 1.4 exam objectives.

Thanks :)

This article has been reviewed and revised repeatedly so as to make it as correct as possible. Thanks a lot to Valentin Crettaz and friends at JavaRanch for suggesting many changes. Especially thanks to Valentin for pointing out the violation of the symmetry requirement by using the instanceof condition in the equals method. If you notice any ambiguity, error in the article and/or the mock test, please do let me know. Your feedback is very important in making this article and test more useful.

kalavat

kalavathi

Rich Internet Application (RIA) Development Guide

The RIA Development Guide from Curl, an award-winning RIA platform company, includes two white papers that will help you choose the best RIA strategy for your company.

Building RIA Beyond AJAX
Rich Internet Applications for the Enterprise
This paper discusses how Curl can help enterprises build applications that go beyond the traditional limitations of web-based applications. Learn how to build RIAs that deliver the full fledged functionality of client/server applications with the flexibility and reach of web-based applications.

RIA Technology Study by Sonata
Triggered by AJAX based popular websites like Google Map, YouTube and Flickr there is now a high demand for next generation Internet applications called RIAs. Surveys by leading research firms indicate that enterprises are taking a closer look at implementing RIAs as they foresee a direct or an indirect influence on their businesses. Enterprises that embark on RIA have a challenging task at hand – choosing the right RIA development platform. The decision is critical as there are many options, vendors and technologies in the market with varying degrees of support for RIA.

kalavathi

Spring into Seam, Part 3: Persistence for two

Who says Web application frameworks can't learn to share? Find out how Spring and Seam can collaborate on persistence tasks in complex, database-oriented applications. (Excerpted from Seam in Action, forthcoming from Manning Publications.)
Dan Allen, May 2008

Web-based spreadsheets with OpenOffice.org and Dojo
If you think that OpenOffice.org is just an open source alternative to Microsoft Office, think again. Find out how it can serve as a component in your Web-based spreadsheet applications.
Oleg Mikheev and Doan Nguyen Van, May 2008

Are applets making a comeback?
Sun is pushing hard for renewal on the client-side with Java SE 6u10, JavaFX Script, and JMC. Are applets ready for a comeback, too? Chet Haase, Cay Horstmann, John Zukowski, Ted Neward, Romain Guy, Jim Weaver, and Danny Coward share their views.
Jeff Friesen, May 2008

The new applet experience
Jeff Friesen puts the newer, faster applet to the test using JavaFX Script and key features of Java SE 6u10.
Jeff Friesen, May 2008

Realistically real-time
Javolution creator Jean-Marie Dautelle benchmarks various methods to reduce the worst-case execution time of Java applications.
Jean-Marie Dautelle, April 2008

More articles >
JW blogs
Everyone loves OSGi

Submitted by Josh Fruhlinger on Wed, 05/21/2008 - 22:30 Here's a great quote, from the blog of JBoss's VP of engineering: "In the last few weeks, the...
0 Comments
Web4J aims to ease your pain

Submitted by Josh Fruhlinger on Wed, 05/21/2008 - 11:06 John O'Hanley, author of the Web4J framework, gives an interview over at DZone. You might remember...
0 Comments
A dubious honor

Submitted by Josh Fruhlinger on Tue, 05/20/2008 - 14:08 Java makes ZDNet UK's list of the most annoying software. "Java doesn't do anything by itself....
1 Comments

More blogs >
Podcasts
JavaWorld's Java Technology Insider

Inside views on essential and emerging Java technologies from the developers shaping the future of the Java platform.

RSS feed
Latest interviews:

* Ken Russell on making applets FAST 05/13/08

* Scott Davis on GIS beyond Google Maps 05/01/08

* Sebastien Arbogast on OSGi and Java modularity 04/03/08

NEWS & VIEWS

SpringSource launches app server
04/30/2008 - Next-generation application server platform based on Spring, OSGi, and Tomcat snubs Java EE.
Chris Kanaracus, IDG News Service

Service Component Architecture: Making SOA easier
04/30/2008 - IBM's Mike Edwards connects the dots between Service Component Architecture, Service Data Objects, and SOA, at OASIS Open Standards 2008 Symposium.
Paul Krill, InfoWorld

JRuby 1.1 released
04/07/2008 - Second major project release features performance improvements, a re-factored IO implementation, and improved memory consumption.
Paul Krill, InfoWorld

Low marks for Eclipse 'integrated everything environment'
04/04/2008 - Still tops for tools integration, a recent survey shows Eclipse losing ground to other IDEs in ease of use, debugging, documentation, and built application performance.
Paul Krill, InfoWorld

Eclipse RT to stress component, runtime efforts
03/17/2008 - Eclipse RT to provide an alternative Java component development model and extend Eclipse technology to servers.
Paul Krill, InfoWorld

More news >
JAVA Q&A
Thursday May 22, 2008

Java Beginner
Learn the basics of client-side Java in this discussion just for beginners. Core topics include the Java Language, the Java Virtual Machine, APIs, and development tools.

Enterprise Java
Get under the hood of the technologies that are shaping the future --- from J2EE to Web services and beyond --- in this discussion for enterprise application developers.

XML & Java
XML has taken off as a practical way to represent data. What are the best tools? This is the place to share ideas about how to take advantage of this emerging technology

Device Programming
Chat about software for devices and gadgets galore and exchange device programming tips with other developers in the field.

Programming Theory & Practice
If you're seeking to hone your programming technique, clean up your code, define a better development process, or simply improve the overall productivity of your day-to-day efforts, this discussion is for you.

Java Security
What does it take to secure Java-based applications, and do the Java Security APIs cover all the bases? Security sleuths talk shop and trade cautionary tales here.

More forums >

* Best of JavaWorld
* Editor's Choice

Some reader favorites:

EJB fundamentals and session beans

Create a scrollable virtual desktop in Swing

HMVC: The layered pattern for client tiers

Double-checked locking: Clever but broken

JW Blogs: The cult of Spring
Obviously when you're up and coming, you gun for those already on top. Nonetheless, JW blogger Josh Fruhlinger is charmed by Web4J creator John O'Hanley's recent comments about the Spring framework, which he notes "has met with a disturbing lack of criticism ..."
Newsletter sign-up

Sign up for our technology specific newsletters.
Enterprise Java
View all newsletters
Email Address:
Featured Whitepapers
Agile Development: Five Steps to Continuous Integration
SOA redefined: Simple. Open. Affordable.
The Four Requirements of Next Generation Web Performance Management
SPONSORED LINKS

See how easy remote support can be. Try WebEx free...
Deliver Support More Efficiently. Remotely Control Applications. Leap Securely t...
Try out WebEx Support Center today for FREE!
Buy a Link Now
Click here to find out more!
More from the IDG Network

Network management as core competency
Computerworld Inc.

WWDC: Why IT staffers, and users, will like Apple's plans
Computerworld Inc.

Microsoft offers online tests of Office 2007
Computerworld Inc.
SPONSORED LINKS

Take Control of Remote Computers.
Support, configure and install applications and updates remotely for greater eff...
Try WebEx Remote Support for FREE

See how easy remote support can be. Try WebEx free...
Deliver Support More Efficiently. Remotely Control Applications. Leap Securely t...
Try out WebEx Support Center today for FREE!

Download MICROSOFT SEARCH SERVER EXPRESS 2008 FREE
Search file shares, SharePoint sites, Exchange Public Folders, Lotus Notes repos...
Deliver Enterprise Search to your Organization Quickly and Easily.

Free DB Modeling Trial with ER/Studio
Design and Build More Powerful Databases with ER/Studio.
www.embarcadero.com

Upload and Share Microsoft Office Documents Online
Share Microsoft Office Documents Online. Sign Up Free Today!
Sign Up Free Today - Workspace.OfficeLive.com
Buy a Link Now

Free Download - 5 Minute Product Review. When slow equals Off: Manage the complexity of Web applications - Symphoniq

Free Download - 5 Minute Product Review. Realize the benefits of real user monitoring in less than an hour. - Symphoniq

kalavathi

Top Job Openings In India
200000+ Jobs, 25000+ Recruiters Apply Now and Start Getting Calls.
Naukri.com

Earn $150 per day or more
within just 30 days Join free today !
www.new-option.com

Jobs for Freshers.
1000's of Jobs in Companies. Submit your Resume Free.Now!
MonsterIndia.com

Jobs
Companies Hiring Urgently. Register & Get An Interview Call Immediately
TimesJobs.com

Post your Resume Here
Shine Presents Career Guidance Tips Along With Top Jobs. Register Today
WinSalary.Shine.com

kalavathi

Download Songs?
Download Songs information Download Songs compare
www.DoorOne.co.uk/Download+Songs

See Beautifull Girls
pictures high all safe download eas Download free videos
www.arcsoc.org

Music Videos On VH1
Watch The Best Guitarists On VH1 Win A "Fender" Guitar Every Week!
www.vh1india.com/godsofguitar

Free online Music
Upload & Share your Favorite Songs Create your Playlist Now!
www.Bigadda.com

XPS™ M1530 Laptop
Dell’s Sleek Laptop for Rs 49,900 With Intel® Centrino® Processor
www.dell.com

kalavathi

http://www4.snapfish.in/shoppingcartintl

kalavathi

Stunning Queenstown
Premier New Zealand Real Estate Property People Performance
www.Bayleys.co.nz

Sonesta Jaco Resort
Luxurious Condo Hotel Jaco Beach Lifestyle purchase for fun & relax.
www.SonestaJaco.com

HDFC Bank Personal Loans
Get Personal Loans Upto Rs 15 Lakhs For Any Purpose Within 72* Hours!
HDFCBankPersonalLoans.co.in

ISM Boston
US-based marketing agency for Travel & Lifestyle brands
www.ismBoston.com

Sobha Lifestyle
One Stop Property Shop. Honest Deals.Call 1 860 500 5559
AllCheckDeals.com/Sobha_Lifestyle

Residence of ideal
Extends Mitsui Fudosan Residential dream ‘iekaki-Residence of ideal’
rakugaki.iekaki.jp/

Life Magazine 1883-2007
Life Magazines available 1883-2007 Time Magazines available 1923-2007
www.MillionMagazines.com

Your Retirement Locator
Quickly find retirement communities senior lifestyles & living choices
www.wheretoliveafter50.com

Flamingo Cove Condos
Costa Rica Luxury Oceanfront Condos Affordable Marina Beach Lifestyle
www.FlamingoCoveCondos.com

Great Jobs For You
Top Jobs in India available at one Go. Register Online with Shine
WinSalary.Shine.com

Related Searches

* MP3s
* Loans
* Jobs
* Music
* Internet
* Flowers
* Shopping
* Fitness
* Education
* DSL

kalavathi

Create Your Own Website
Free Drag & Drop website builder very easy to use. No HTML to learn
www.bluevoda.net

small Business Web Sites
EditMe is a flexible and affordable service with easy in-browser edits
www.editme.com

Get own website @ Rs.4200
10 Pages website with flash header, 1 Domain, 25 MB webspace, 1 form
www.coraleye.com

Offshore Development
Cost Effective Software Development US Headquartered, Centers Worldwide
www.v2soft.com/

Need a Website? Save Now
Get your .COM for only $6.85 Today! Free Hosting, Email, Blogcast, More
GoDaddy.com

Get Paid While you Sleep
Your Website Will Earn Millions Create Easily. Join Free Right Now
www.smartpreparation.com

Website: Create Your Own
Make a website without programming hosting, builder, ecommerce, domain
www.SiteRightNow.com

Multi-Streams of Money?
Your Vision - Your Desire Your Action Now is Your Success!
www.pidwarko.com

Affordable Web Services
Professional and Affordable Web Site design and development company
www.AdasTechnologies.com

EeRabbit Logo Design $99
100% satisfaction guarantee logo design with stationery designs
www.EeLogo.com