Container sorting with respect to the hierarchy

I needed the sorting of a HierarchicalContainer to respect the item hierarchy. By default the container simply sorts all items equally so the displayed hierarchy is mixed up, e.g. in a table.

Because all fields are private in both IndexedContainer and HierarchicalContainer I came to the following solution:

public class HierarchicalSortableContainer extends HierarchicalContainer
{
	private static final long serialVersionUID = 1L;

	@Override
	public int compare(Object o1, Object o2)
	{
		LinkedList<Object> path1=getHierarchiePath(o1);
		LinkedList<Object> path2=getHierarchiePath(o2);
		
		do
		{
			Object p1=path1.removeFirst();
			Object p2=path2.removeFirst();
			
			if(p1==p2 || (p1!=null && p1.equals(p2))) continue;
			else 
			{
				int result=super.compare(p1,p2);
				if(result!=0) return result;
			}
		}
		while(!path1.isEmpty() && !path2.isEmpty());
		
		if(path1.isEmpty())
		{
			if(!path2.isEmpty()) return -1;
		}
		else if(path2.isEmpty()) return 1;

		return 0;
	}
	
	/**
	 * Generates the path of parents for an item
	 * @param itemId The id of the item
	 * @return The "tree" path of the item
	 */
	protected LinkedList<Object> getHierarchiePath(Object itemId)
	{
		LinkedList<Object> path=new LinkedList<Object>();
		path.add(itemId);
		for(Object currentId=getParent(itemId);currentId!=null;currentId=getParent(currentId))
		{
			path.push(currentId);
		}
		return path;
	}
}