0

I'm creating a program using LinkedList that could copy duplicate numbers to a new instance of linkedList.

Let's say List<Integer> orig = new LinkedList<>() consists of these numbers: 23,1000,1000,1,23 I want to copy the duplicate numbers to List<Integer> copy = new LinkedList<>() which supposed to be 23 and 1000 because I have 2 duplicate numbers. I tried testing it in an array and it works. But not sure why it won't work in LinkedList.

List<Integer> list1 = new LinkedList<>();
    list1.add(23);
    list1.add(1000);
    list1.add(1000);
    list1.add(1);
    list1.add(23);
    List<Integer> list2 = new LinkedList<>();
    for(int x = 0; x <= list1.size()-1; x++) {
        for(int y = x+1; y <= list1.size()-1; y++) {
            if(list1.get(x)==list1.get(y)) {
                list2.add(list1.get(x));
            }
        }
    }

    for(int y = 0; y <= list2.size()-1; y++) {
        System.out.println(list2.get(y));
    }
  • Current OUTPUT: 23
  • Expected output is: 23,1000
azro
  • 53,056
  • 7
  • 34
  • 70

3 Answers3

3

To add an explanation to the existing answers:

In Java there are two ways of comparing things - == and equals, where the latter is required for comparing objects (short version, for details see What is the difference between == and equals() in Java?). So the correct way of comparing two Integers is indeed x.equals(y).

The reason why your output still contained "23" is Java's integer cache. The Java specification explicitly requires that x == y is true for all numbers between -127 and +128 (also short version, for details see Integers caching in Java).

Short demo:

Integer a1 = 23;
Integer a2 = 23;
Integer b1 = 1000;
Integer b2 = 1000;
System.out.println(a1 == a2);      // true
System.out.println(a1.equals(a2)); // true
System.out.println(b1 == b2);      // false
System.out.println(b1.equals(b2)); // true
Marvin
  • 13,325
  • 3
  • 51
  • 57
1

Your manipulating Integer, they are object, you may compare them with .equals() not == that check for reference

Set this, and it'll be ok :

if (list1.get(x).equals(list1.get(y))) {
    list2.add(list1.get(x));
}

Also, to look on a List indexes, use x < list1.size() instead of x <= list1.size() - 1, you can also use for-each

for (Integer integer : list2) {
    System.out.println(integer);
}
azro
  • 53,056
  • 7
  • 34
  • 70
1

Use equals for comparison instead of ==

List<Integer> list1 = new LinkedList<>();
    list1.add(23);
    list1.add(1000);
    list1.add(1000);
    list1.add(1);
    list1.add(23);
    List<Integer> list2 = new LinkedList<>();
    for(int x = 0; x <= list1.size()-1; x++) {
        for(int y = x+1; y <= list1.size()-1; y++) {
            if(list1.get(x).equals(list1.get(y)) {
            list2.add(list1.get(x));
        }
    }
}

for(int y = 0; y <= list2.size()-1; y++) {
    System.out.println(list2.get(y));
}