0

I am trying to find the index of an element after a particular position in ArrayList in Java as mentioned in this question. Below is my implementation:

import java.io.*;
import java.util.*;
class palindrome{
    public static void main(String[] args)throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int n=array[0];
        List<StringBuilder> ls=new ArrayList<StringBuilder>();
        while(n-->0){
            ls.add(new StringBuilder(br.readLine()));
        }
        StringBuilder rev=ls.get(1).reverse();
        System.out.println(rev);
        int i=1;
        System.out.println(ls.subList(i+1,ls.size()).indexOf(rev));
    }
}

I'm giving below input to the program

4 2
oo
ox
xx
xo

so, the logic is that I am trying to find the index of reverse of 'ox', which should return 3, but the code always returns -1. I cannot spot any error. Please tell me if you guys have spotted any error.

Thank You!

3
  • so simply: remove the counting code for a moment, and test it with hardcoded knowledge of the fact that you're only going to be inputting ox. And then step through it with debugging turned on: what happens at each line? Commented May 28, 2020 at 16:14
  • Sorry, but I'm using simple text editor. I cannot do debugging. I am hardcoding 'xo' inside indexOf Commented May 28, 2020 at 16:18
  • Then step one is to start using a proper code editor. Whether it's Eclipse or VS Code, real code editors help you solve problems rather than needing to ask people to help you, so: now is the best time to start using one. Commented May 28, 2020 at 16:20

1 Answer 1

5

StringBuilders are work-in-progress strings being built and as such they don't override equals(). A string builder will only compare equal to itself. It's never equal to any other builders, not even ones with the same contents.

That means that indexOf() won't work because it relies on equals(). If you want this to work you need to use plain Strings rather than StringBuilders. For example:

List<String> ls = new ArrayList<>();
while (n-- > 0) {
    ls.add(br.readLine());
}
String rev = new StringBuilder(ls.get(1)).reverse().toString();

Or, if you want to stick with StringBuilders you can, you'll just have to forego the indexOf() method and look for the matching string yourself with a manual for loop.

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.