Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to compare two data structures in java

Tags:

java

I would like to know what is the fastest way in java 1.5 to compare two data structures.

My data structure represents a tree that can be pretty big. I can traverse the whole data structure and compare the 2 node by node (which I guess will be slow). Or I can compute a hash of the data structure to do it faster, right ?

What is the best (efficient and not too long) way to compute this hash ?

I wouldn't like to need too much time to compute hash...

Hope I'm clear.. :-)...

like image 470
LB40 Avatar asked Apr 17 '09 17:04

LB40


People also ask

How do I compare two sets of data in Java?

The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.

Can we compare two methods in Java?

The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)

How do I compare two lists in Java?

Java provides a method for comparing two Array List. The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.

Which of these data structures provides the most consistent performance for both insert and search?

Binary Search Trees (BST)


2 Answers

Have you considered keeping a running hashCode which is continually updated as elements are inserted or removed from your trees? This way, comparing a tree at any given time by hashCode will be instantaneous.

Depending on how you implement your hash function, and how frequently you insert and remove nodes, this could be a horrible solution. If your hash function is fast, you aren't making many changes, and you need to do a lot of comparisons, this could work.

like image 117
gdm Avatar answered Oct 08 '22 01:10

gdm


Every object inherits .equals() and .hashCode() from Object.

The standard data-structures in Java should already implement a relatively fast .hashCode() method for you (The hash might be incrementally calculated or might require iterating over each element, check the source of the data-structure you're using to be sure).

You should be aware that hash collisions might occur even if the data-structures aren't identical.

To have an accurate comparison I would perform a tree traversal simultaneously on both tree comparing each element. This way the shape of the tree as well as the contained elements would be compared in O(n) time where n is the size of the largest tree.

like image 30
Ben S Avatar answered Oct 08 '22 01:10

Ben S