排序列表(降序)

时间:2014-09-05 18:20:52

标签: java list sorting

我如何排序此列表(降序)?它会添加数字,但会按升序对其进行排序,但我希望它能够降序(不使用任何外部库或任何东西)。我试图解决它,但没有想出任何东西。

private void addNewElement()
{
//getting the input
System.out.print("Please type the number to be added to the list: ");

Integer newValue = null;
while(newValue == null)
{
    try
    {
        newValue = Integer.parseInt(userInput.nextLine());
    }
    catch (final Exception e)
    {
        System.out.println("Wrong value. Please insert new value.");
    }
}

//creating new element based on the input
MyListElement newElement = new MyListElement(newValue);

//if not first
if (firstElement != null)
{
    placeElementInList(newElement);
}
else
{
    firstElement = newElement; //if first
}
}

//if not first
private void placeElementInList(final MyListElement newElement)
{
//if smaller than first
if (newElement.value < firstElement.value)
{
    newElement.nextElement = firstElement;  //new points to first
    firstElement = newElement;              //and becomes first
}
else
{
    MyListElement previousElement = firstElement; //have to remember previous element
    MyListElement elementInList = firstElement.nextElement;  //currently checked.
    while (elementInList != null)
    {
        if (newElement.value < elementInList.value)  //if new element is smaller that currently checked
        {
            break;  //break - put it in current position.
        }
        previousElement = elementInList; //if not, move forward, substitute variables
        elementInList = elementInList.nextElement;
    }
    previousElement.nextElement = newElement;  //set the new element at the proper position
    newElement.nextElement = elementInList;    //
}

}

1 个答案:

答案 0 :(得分:0)

要让它按降序排序,只需将所有比较运算符从<翻转到>,例如

if (newElement.value > firstElement.value)