0

This code checks if a linked list is a palindrome.

When I compare the two values in my list that are greater than 127 it will return that the values are always not equal for example running [1, 128, 100, 100, 128, 1] the code will return 128 != 128 unless I cast them to int within the if statement.

I'm just curious as to why this is happening. Here's my code:

while(firstHalf != null && secondHalf != null)
    {
        //COMPARISON ONLY WORKS WHEN CASTED TO AN INT
        if(((int)firstHalf.value) != ((int)secondHalf.value))
        {
            return false;
        }
        firstHalf = firstHalf.next;
        secondHalf = secondHalf.next;
    }

Entire method:

// Definition for singly-linked list:
// class ListNode<T> {
//   ListNode(T x) {
//     value = x;
//   }
//   T value;
//   ListNode<T> next;
// }
//
boolean isListPalindrome(ListNode<Integer> l) {
    if(l == null)
        return true;

    ListNode fastPnter = l;
    ListNode slowPnter = l;
    ListNode slowPnterPrev = l;

    //find mid point
    while(fastPnter != null && fastPnter.next !=null)
    {
        fastPnter = fastPnter.next.next;
        slowPnterPrev = slowPnter;
        slowPnter = slowPnter.next;
    }

    //odd case
    if(fastPnter != null)
    {
        slowPnterPrev = slowPnter;
        slowPnter = slowPnter.next;
    }

    //reverse second half
    slowPnterPrev.next = null;
    ListNode midNode = reverse(slowPnter);

    //check halves
    ListNode firstHalf = l;
    ListNode secondHalf = midNode;
    while(firstHalf != null && secondHalf != null)
    {
        //COMPARISON ONLY WORKS WHEN CASTED TO AN INT
        if(((int)firstHalf.value) != ((int)secondHalf.value))
        {
            return false;
        }
        firstHalf = firstHalf.next;
        secondHalf = secondHalf.next;
    }

    return true;
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146

2 Answers2

3

Without the explicit cast to int, the values in your list are being treated as an Integer (as can be seen from the parameter definition ListNode<Integer> l).

In order to correctly compare Objects (like two Integers), you should use the .equals() method rather than ==. When you use ==, you are actually comparing that the integers point to the same memory address. The JVM caches Integer values between -128 and 127, so that's why the code only works for those values.

(See http://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching)

Jared Stewart
  • 571
  • 3
  • 10
0

Integer class has internal cache for instances representing numbers from -128 to 127. Use equals method to compare Integers

ptomala
  • 1
  • 1