Reputation: 305
I'm looping in for loop to check the substring of the elements: example: titles-->[Manager, Marketing Manager, Sales, Sales and Marketing Manager] Expected Result: [ Sales and Marketing Manager] Since manager is the substring of Marketing Manager I am removing the element manager, then Sales is the Substring of Sales and Marketing Manager so I am removing sales element from the array and also marketing Manager is the substring of Sales and Marketting Manager so removing Marketing Manager From the list so finaly output will be [Sales and Marketing Manager]
static String removeSecWords(List<String> titles) {
for (int j = 0; j < titles.size(); j++) {
for (int k = 0; k < titles.size(); k++) {
if (j == k)
continue;
if (titles.get(j).contains(titles.get(k))) {
titles.remove(k);
}
}
}
return (titles.toString());
}
I am getting error IndexOutOfBounds exception can any tell me how do this.
Upvotes: 0
Views: 181
Reputation: 37645
If you remove from titles
, j
could become equal to titles.size();
, so next time you try titles.get(j)
you get an IndexOutOfBoundsException
. To fix your code, you need to think what to do about both k
and j
.
When you remove from titles
, you do not want to increment k
because otherwise an element will get skipped. I've written k--;
as a quick and lazy fix, but normally I do not recommend changing the index in a traditional for
loop.
Also, if j
is after the position you remove at, you need to change the j
index too, so it still refers to the same element. Try this version:
for (int j = 0; j < titles.size(); j++) {
for (int k = 0; k < titles.size(); k++) {
if (j != k && titles.get(j).contains(titles.get(k))) {
titles.remove(k);
if (j > k)
j--;
k--;
}
}
}
Upvotes: 0
Reputation: 3079
your code is unsafe: you remove things in the list, and in the same time, you use size(). You have to separate this.
one solution with a separate Set:
static String removeSecWords(List<String> titles) {
// Keep all at begining
Set<String> to_keep=new HashSet<String>();
for (int j = 0; j < titles.size(); j++)
to_keep.add(titles.get(j));
for (int j = 0; j < titles.size(); j++) {
for (int k = 0; k < titles.size(); k++) {
if (j == k)
continue;
if ((to_keep.contains(titles.get(j)) && (to_keep.contains(titles.get(k)))))
if (titles.get(j).contains(titles.get(k)))
{
to_keep.remove(titles.get(k));
}
}
}
return (to_keep.toString());
}
Upvotes: 3