• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 167
  • 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 KwanAnalyst ProgrammerCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

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