How to achieve pass by reference in recursive methods in Java

What are the ways in which we can achieve/mock pass by reference in Java? In order to check whether a linkedlist is a palindrome, i wrote the below code. It works/ But i would like to know if there are any other ways to achieve this without wring a wrapper class.

   class MyClass {
        ListNode mover = head;
        boolean b = true;
    }

public boolean checkPalindrome(){

        ListNode temp = head;

        int len = length()/2 + length()%2;

        MyClass myObj = new MyClass();

        int i =(len%2 == 1) ? len:len-1;

        while(i>1){
            myObj.mover = myObj.mover.next;
            i--;
        }
        boolean e = checkPalindrome(temp, myObj, len);
        return e;
    }

    public boolean checkPalindrome(ListNode head, MyClass ref, int len) {

        if(head == null || len == 0)
            return true;

        len = len-1;

        checkPalindrome(head.next,ref, len);
        ref.mover = ref.mover.next;
        ref.b = ref.b && (head.value==ref.mover.value);
        return ref.b;
    }

In order have the current location of "ref" object i wrote the MyClass wrapper. Is there a better way than this?

Jon Skeet
people
quotationmark

You only need the extra class because you've got two pieces of information to maintain - and you've only got two pieces of information to maintain because you're ignoring the return value of the recursive call. I suspect that you could change your code to use AtomicReference instead:

public boolean checkPalindrome(ListNode head,
                               AtomicReference<ListNode> tailRef,
                               int len) {
    if (head == null || len == 0) {
        return true;
    }

    len--;

    boolean ret = checkPalindrome(head.next, tailRef, len);
    ListNode tail = tailRef.get().next;        
    tailRef.set(tail);
    return ret && head.value == tail.value;
}

I haven't checked it thoroughly, but if it's not quite there, you should be able to fix it fairly easily.

people

See more on this question at Stackoverflow