Reputation: 667
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!
Upvotes: 0
Views: 194
Reputation: 361605
StringBuilder
s 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 String
s rather than StringBuilder
s. 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 StringBuilder
s you can, you'll just have to forego the indexOf()
method and look for the matching string yourself with a manual for
loop.
Upvotes: 5