1

I have an ArrayList<String> A that contains n elements, and an ArrayList<Integer> B that contains the indexes from A that I need to delete. How can I delete these indexes? After I remove an index like this : A.remove(index), then the size of A is smaller and the others indexes are not on the same position anymore.

Any idea is welcome.

3
  • you may want to consider another data structure as this doesn't seem like a great solution (I don't know what you're trying to do). Maybe talk about what you want to do and I think we could have a fun discussion of how best to implement it :P Commented Oct 29, 2012 at 16:07
  • Why are you not using a HashMap or SparseArray rather than two different ArrayLists? It sounds like the two items are correlated with each other, keep them in a HashMap or SparseArray and then they are directly linked and can be removed in one call. Commented Oct 29, 2012 at 16:08
  • I agree with HashMap but I will add that you will want to check out LinkedHashMap if you want the items to keep the same order. Commented Oct 29, 2012 at 16:15

4 Answers 4

3

You have to sort them (Collections.sort() probably works out of the box for integer arraylist), and start by removing the bigger index first.

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

Comments

3

If you don't have duplicate Strings in your list you can create a list with the objects you want to remove and then call the removeAll(Collection c) method for your array list.

if stringList is the list with your Strings and indexList is the list of your index:

List<String> toRemove = new ArrayList<String>();

for(Integer i : indexList){
 toRemove.add(stringList.get(i));
}
stringList.removeAll(toRemove);

Comments

0

The behaviour you're looking for is best achieved using a different data structure. I myself thought of a HashMap (see also: Map).

Comments

0
    for(int i = 0; i < arrayListInt.size(); i++){
    int arrayIndexInIntArray = arrayListInt.get(i);
    int arrayIndexToRemove = 0;
        for (Iterator iterator = arrrayList.getIterator(); iterator.hasNext();) {

                                    String tempString = (String) iterator.next();
                                    if (arrayIndexInIntArray == arrayIndexToRemove) { //Some condition
                                        iterator.remove();//Remove the value at the current iterator
break;
                                    }
arrayIndexToRemove ++;
    }
                                }
    }

Try this.

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.