I am making a array list of items and changing its contents occasionaly.The problem is that after removal of an item from the array list,the sequence of items become destorted and the array list looses its sorting.I searched a lot but did not get any idea about how to keep the array list sorted after removal of items from it.This is the code i am using:
ArrayList<String> m_namesOfContactsArrayList = new ArrayList<String>();
for(int i = 0;i < 100;i++)
m_namesOfContactsArrayList.add(i);
This is where i am removing the items:
m_namesOfContactsArrayList.remove(3);
m_namesOfContactsArrayList.remove(4);
m_namesOfContactsArrayList.remove(5);
Please help me.Thanks in advance.
Deletion of an element doesn’t affect the order of the elements.
Just to demonstrate it on your code:
ArrayList m_namesOfContactsArrayList = new ArrayList();
Before removal:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After removal:
[0, 1, 2, 4, 6, 8, 9]
The three elements are gone, but the list is still sorted.
Btw, the java
Listis intended to be sorted by the insertion order. If you want to order the elements by some specific criteria, you can use e.g. aSortedSet, likeTreeSet