• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 162
  • Last Modified:

What is the best way to compare the contents of the instances of Hashtable?

What is the best way to compare the contents of the instances of Hashtable? The keys are Strings and the values are Integer. It doesnt have to be the same referenced instances, the matter is only if strings are equal character wise and the integer values are the same.
0
Suppai
Asked:
Suppai
2 Solutions
 
Peter KwanCommented:
If I don't get your question wrong, I think the following algorithm should work for you (using commons-collections package):




import org.apache.commons.collections.map.*;
 
public class TestMultiValueMap {
   public static void main(String[] args) {
      MultiValueMap map1 = new MultiValueMap ();
      for (Iterator it = ht1.keySet().iterator(); it.hasNext(); ) {
           String key1 = it.next();
           Integer val1 = ht1.get(key1);
           map1.put(new Integer(key1.length()), val1);
      }
      for (Iterator it = ht2.keySet().iterator(); it.hasNext(); ) {
           String key1 = it.next();
           Integer val1 = ht1.get(key1);
           System.out.println(map1.containsValue(new Integer(key1.length()), val1));
      }
   }
}

Open in new window

0
 
CEHJCommented:
You could do
boolean mapsEquals = m1.equals(m2);

Open in new window

0
 
SuppaiAuthor Commented:
The equals will work for the purpose? I thought it needed to reference the same instance in order to work? Or is that compareTo?
0
 
objectsCommented:
In your case you can use equals()
the javadoc defines it to be equal using

"More formally, two maps t1 and t2 represent the same mappings if t1.keySet().equals(t2.keySet()) and for every key k in t1.keySet(), (t1.get(k)==null ? t2.get(k)==null : t1.get(k).equals(t2.get(k)))"

You just need to be sure your object in your map correctly implement equuals. Which in your case they do.

Let me know if you have any questions.

0
 
objectsCommented:
>  I thought it needed to reference the same instance in order to work?

Thats the default, individual class can implement their own equals method
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now