Click here to Skip to main content
15,909,242 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

Suppose you need to determine whether two ArrayLists are equal except you don't care whether the orders of the elements in the two lists are the same. Here is one method that purportedly solves this problem:
Java
    public boolean specialArrayListEquals(ArrayList a1, ArrayList a2){
    	boolean result = true;
    	a1 = new ArrayList(a1);  //create a clone of a1
    	a2 = new ArrayList(a2);  //create a clone of a2
if(a1.size() == a2.size()) {
    		for(int i = 0; ((i < a1.size()) && (result == true)); i++){
    			Object o = a1.get(i);
    			result = a2.contains(o);
    			if(result){ // remove the equal elements from both
    				a1.remove(o);
    				a2.remove(o);
    			}
    		}
    	}
    	return result;
    }

Debug this code, list everything you can think of that makes this code inelegant, and then come up with an elegant solution to the problem. Can you come up with an even more elegant solution if you know that there are no duplicate elements (that is, no two equal elements) in each ArrayList?

Thanks
sujan.
Posted
Updated 3-Nov-11 19:08pm
v2
Comments
nagendrathecoder 4-Nov-11 1:25am    
Use question heading related to actual topic.

1 solution

The solution you show is also ineffective as the methods remove and contain works at the speed of O(n). (For understanding "Big O Notation", see http://en.wikipedia.org/wiki/Big_O_notation[^].)

Speed considerations and the no-duplicate constrain suggest the use of java.util.Hashtable, see http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html[^] at the expense of some memory overhead. For big collections, this class provides the speed about O(1) (no dependency on the size of collection, constant search time for big collections).

You can populate an instance of hash table from one list and try to find the elements of another list one by one. The rest of this algorithm is simple, so I would leave to for your home exercise :-).

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900