Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two problems with your code. First, when <code>j == size - 1</code> (the last iteration), you are calling list.get(j+1), which is what is causing the exception. Just change your loop condition to <code>j &lt; size - 1</code> and the exception should go away. (Alternatively, start at <code>j = 1</code> and compare to the previous element.)</p> <p>Second, you are only comparing each element with its immediate successor element. From your description, it doesn't sound like that's what you want to do.</p> <p>I'd suggest capturing the logic of comparison in a separate method. It might be part of <code>MyClass</code>:</p> <pre><code>class MyClass { String str; Integer intgr; /** * Returns the relationship between this and another MyClass instance. * The relationship can be one of three values: * &lt;pre&gt; * -1 - This object should be discarded and other kept * 0 - There is no relationship between this and other * 1 - This object should be kept and other discarded * &lt;/pre&gt; * * @param other The other instance to evaluate * * @return 0 if there is no relationship. */ public int relationTo(MyClass other) { final String myPrefix = str.substring(0, str.length() - 1); final String otherPrefix = other.str.substring(0, other.str.length() - 1); if (myPrefix.equals(otherPrefix)) { return intgr &lt; other.intgr ? -1 : 1; } else { return 0; } } } </code></pre> <p>(This can easily be transformed into a method with two arguments that would be outside <code>MyClass</code>.) Then you can use the method to decide what to keep. You need to do a double iteration to find non-adjacent objects:</p> <pre><code>int size = list.size(); for (int i = 0; i &lt; size; ++i) { final MyClass current = list.get(i); for (int j = 0; j &lt; i; ++j) { final MyClass previous = list.get(j); final int relation = previous.relationTo(current); if (relation &lt; 0) { // remove previous (at index j) list.remove(j); --i; --j; --size; } else if (relation &gt; 0) { // remove current (at index i) list.remove(i); --i; --size; break; // exit inner loop } // else current and previous don't share a prefix } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload