How to get the intersection of two arraylist containing user defined obj?

How to get the intersection of two arraylist containing user defined obj?

I can easily get the intersection of two array list which containing some simple class(Integer, String). But how to get the intersection of two arrayList which contain user defined object?

Here is the sample code..I can not run this out...anybody can help me? thank you very much..

The correct result should be like this:

2

2

but I can only get this:

2

0

-

import java.util.*;

public class testRetain{

public static void main(String[] args){

ArrayList a = new ArrayList();

ArrayList b = new ArrayList();

a.add( new dog(1,2,2) );

a.add( new dog(1,2,1) );

System.out.println(a.size() );

b.add( new dog(1,2,2) );

a.retainAll(b);

System.out.println(a.size() );

}

}

class dog implements Comparable{

int head;

int arms;

int legs;

dog(int head, int arms, int legs){

this.head = head;

this.arms = arms;

this.legs = legs;

}

public int compareTo(Object o){

if ( ((dog)o).head > this.head )

return -1;

else if ( ((dog)o).head < this.head )

return 1;

else

return 0;

}

}

[1285 byte] By [Nickolas.Chena] at [2007-11-27 3:50:46]
# 1
@Op. Your classes should override equals and hashCodeKaj
kajbja at 2007-7-12 8:54:42 > top of Java-index,Java Essentials,Java Programming...
# 2
That works! Thanks Man...
Nickolas.Chena at 2007-7-12 8:54:42 > top of Java-index,Java Essentials,Java Programming...