0

I am designing a util class that takes a string as a parameter and returns true if it is a palindrome(ex: input: radar ---> output: true) and returns false if it is not. For this class, I am using a linkedlist, however I don't know why there seems to be an error. Here is the stack trace:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
    at java.util.LinkedList.remove(LinkedList.java:525)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:20)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:16)
    at com.run.Test.main(Test.java:7)

And Here is the source code:

public boolean FindMain(String in){
    if(times == 0){
    search = new LinkedList(cc.convertStringToArraylist(in)); 
    times ++;
    FindMain(null);
    } else {
        if(search.get(search.size()-1).equals(search.get(0))){
            search.remove(0);
            search.remove(search.size());
            FindMain(null);
        } else {
            System.out.println("Not Palindrome");
            return false;
        }
    }

    return true;

}

1 Answer 1

3

search.remove(search.size()) should be search.remove(search.size() - 1) since lists are zero-based. If you have four elements your list indices run from 0 to 3, and so there is nothing at location 4.

Also your code as it stands won't handle empty lists very well, so that's something you need to check.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.