Here's some code I've had to write more than once. It inserts something into a list at a position based on the compareTo method. Consequently the element inserted must imlpement this.
public void addElement(MyElement aElement)
{
List myElementsList = this.getMyList();
// Check that the list exists
if (myElementsList == null)
{
myElementsList = new ArrayList();
}
// Check that the list is not empty
if (myElementsList.size() == 0)
{
myElementsList.add(0, aElement); // add the element at the beginning
return;
}
MyElement currentElement;
for (int index = 0 ; index < myElementsList.size() ; index++)
{
currentElement = (myElement) myElementsList.get(index);
// if the current element has the same compareTo value as the element to be added
if (currentElement.compareTo(aElement) == 0)
{
// The hearing is already in the list. Take no further action and return
return;
}
// else if the current element is before the element to be added
else if (currentElement.compareTo(aElement) < 0)
{
myElementsList.add(index, aElement);
return;
}
}
}
}