2

My code is working for 1 and 2 digit numbers but not for numbers > 2 digits

public class remove_duplicates {

    public static node<Integer> takeInput() {
        Scanner s = new Scanner(System.in);
        int data = s.nextInt();
        node<Integer> head = null;
        while (data != -1){
            node<Integer> newNode =new node<Integer>(data);
            if(head == null){
                head = newNode;
            }
            else {
                node<Integer> temp =  head;
                while(temp.next != null){
                    temp = temp.next;
                }
                temp.next =newNode;
            }
            data = s.nextInt();
        }
        return head;
    }

    public static node<Integer> removeDuplicates(node<Integer> head){
            node<Integer> current = head;    
            while(current.next != null){
                if(current.data == current.next.data){
                    current.next = current.next.next;
                }
                else
                    current = current.next;
            }

            return head;
        }


    public static void print (node<Integer>head){
        node<Integer> temp = head; 
        while (temp != null) 
        { 
            System.out.print(temp.data+" "); 
            temp = temp.next; 
        }   
        System.out.println(); 

    }

    public static void main(String[] args) {
        node<Integer> head = takeInput();
        node<Integer> data = removeDuplicates(head);
        print(data);
    }
}
  • My output: 281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953

  • Expected output: 281 386 957 1022 1216 1232 1364 1428 1501 1953

Why is it working for 1/2 digits integers and not for 3 digits or more? How can I solve this issue?

Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51

1 Answers1

3

Solution

Use equals(). At removeDuplicates function change the line if(current.data == current.next.data) by the following: if(current.data.equals(current.next.data))

Rationale

You should always use equals() to compare a particular value of two objects and not ==. The reason of that is because == compares object references and equals() compares the value of that object. That value will depend on your needs and you could set your particular comparison criteria, but for native types wrappers like Integer it compares by default the number and not the objects adresses -which is what you get by using ==-.

Why == works for one/two digits Integer?

When the value of an Integer is in the range of [-128; 127] Java uses a cache to store numbers, so if a number is in the cache, it re-use that object. So the reference == will work, because they are referencing the very same object. On the other hand, if you use an integer greater than 127 or lower than -128, it won't work because Java will create different objects outside of the cache scope.

Tomás Juárez
  • 1,517
  • 3
  • 21
  • 51