471,893 Members | 2,056 Online

# Comparing Two Lists for common elements

My Assignment was to compare two lists and print out the number of elments that are same.

It is supposed to look like this

Week 7 Homework
The number of common elements is: 3
The number of common elements is: 3

I get

Week 7 Homework
The number of common elements is: 0
The number of common elements is: 1

Which is better than my many other attempts, if you could offer any help I would appreciate it.

JoeMac3313

Expand|Select|Wrap|Line Numbers
1. import ch06.lists.*;
2.
3. public class CompareListsTest
4. {
5.
6.    private static int compareUnsortedLists(UnsortedListInterface list1, UnsortedListInterface list2) {
7.
8.     int counter = 0;
9.
10.         list1.reset();
11.         list2.reset();
12.
13.         if(list2.contains(list1.getNext())&& list1.getNext() != null)
14.         {
15.             counter++;
16.         }
17.
18.     return counter;
19.
20.    }
21.
22.
23.    public static void main(String[] args) {
24.
25.       // declare and populate list lst1
26.       UnsortedListInterface lst1 = new RefUnsortedList();
33.
34.      // declare and populate list lst2
35.      UnsortedListInterface lst2 = new RefUnsortedList();
41.
42.      // Self introduction
43.      System.out.println("Week 7 Homework");
44.
45.      // Call compareUnsortedLists
46.      System.out.println("The number of common elements is: " + compareUnsortedLists(lst1, lst2));
47.
48.      // The property should be symetric and therefore the same result should be
49.      // obtained if the parameters are swapped in the method call
50.      System.out.println("The number of common elements is: " + compareUnsortedLists(lst2, lst1));
51.
52.   }
53.
54. }
55.
56.
57.
58.
Jul 14 '07 #1
3 34471
JosAH
11,448 Expert 8TB
If your lists contain n and m elements respectively you have to perform n*m
comparisons. If the elements nicely implement the equals() and hashCode()
methods you can the lists figure out the presence of an element. It would clean

Expand|Select|Wrap|Line Numbers
1. List<YourType> listA= ...
2. List<YourType> listB= ...
3. int common= 0;
4. for (YourType element: listA)
5.    if (listB.contains(element))
6.       common++;
7.
kind regards,

Jos
Jul 14 '07 #2
I fixed it w/ this code. Thanks for the help!

Expand|Select|Wrap|Line Numbers
1.
2. int counter = 0;
3. int count = 0;
4.
5.     list1.reset();
6.
7.     while(counter < list1.size())
8.     {
9.         if(list2.contains(list1.getNext()))
10.         {
11.             count++;
12.         }
13.
14.         counter++;
15.     }
16.
Jul 14 '07 #3
JosAH
11,448 Expert 8TB
I fixed it w/ this code. Thanks for the help!
Good; you're welcome and best of luck with your Java projects.

kind regards,

Jos
Jul 14 '07 #4