How to sort an ArrayList in Java

  Uncategorized

If you want to sort any ArrayList in java, you need to make sure, your objects in the arrylist are comparable. This is done by using implements Comparable and implementing the abstract method compareTo (T cmp). For example if you want to sort some highscores you can do it like this.

public class Highscore implements Comparable
{

	@Override
	public int compareTo(Highscore cmp)
	{
		if (cmp.getAnzQuad() > getAnzQuad())
		{
			return -1;
		} else {
			return 1;
		}
	}

	...
public class Highscores
{
	....

	public ArrayList getHighscores ()
	{
		ArrayList ret = new ArrayList();
		...
		// Fill the ret ArrayList with your highscores	

		// Sort the highscores with Collections.sort
		Collections.sort(ret);	
		return ret;
	}

This is a simple, but powerfull solution to sort an ArrayList.