Java 对列表排序(降序)
我怎样才能按降序排列这个列表?它添加数字,但按升序排序,但我希望它是降序的,而不使用任何外部库或任何东西。我想弄明白,但什么也没想出来Java 对列表排序(降序),java,list,sorting,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
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; //
}
}要进行降序排序,只需将所有比较运算符从
使用Collections.sort和比较器。降序与升序相同,只是翻转了符号。您应该能够通过更改一行代码来更改另一行代码。ifnewElement.value>elementInList.value…好的,但是如果在列表已经完成时我应该按降序排序呢?我是说,在我要打印的时候。如下:MyListElement元素列表=第一个元素;而元素列表!=null{System.out.printelementInList.value+,;elementInList=elementInList.nextElement;}您可以通过交换第一个和最后一个元素、第二个和第二个到最后一个元素等来反转列表,直到到达列表的中间。那么,我应该使用while循环吗?对不起,我真的很困惑
if (newElement.value > firstElement.value)