java 使用 Comparable 接口对 ArrayList 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16268896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort ArrayList using Comparable interface
提问by user2317377
I am working on an assignment. I have the basics down of what I need done, but for some reason, the compareTo is not sorting properly on one set of example inputs. The first set of inputs sorts properly and returns the right value, but the second set rearranges, but does not sort. Basically I have an object Cow, that has a time and a number of flowers eaten. I want to take these objects and sort them, first by time, shortest time first, and then by flowers eaten, largest amount first. So if I had 3 cows, 1 and 10, 2 and 5, 2 and 7. I would sort them, first, third and second. Hopefully that makes sense. I am not sure why the Collection.sort is not working as intended...but hopefully someone can lead me in the right direction of what I am doing wrong.
我正在处理一项任务。我有我需要做的事情的基础知识,但由于某种原因, compareTo 没有在一组示例输入上正确排序。第一组输入正确排序并返回正确的值,但第二组重新排列,但不排序。基本上我有一个对象 Cow,它有一个时间和一些吃过的花。我想把这些东西拿来排序,先按时间,时间最短的,然后是吃的花,数量最多的在前。所以如果我有 3 头奶牛,1 和 10,2 和 5,2 和 7。我会对它们进行排序,第一,第三和第二。希望这是有道理的。我不确定为什么 Collection.sort 没有按预期工作......但希望有人能引导我朝着正确的方向走我做错了什么。
Here is my code so far:
到目前为止,这是我的代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Flowers {
public static void main(String[] args) {
ArrayList<Cow> list = new ArrayList<Cow>();
Scanner input = new Scanner(System.in);
final int numOfCows = Integer.parseInt(input.next());
int totalFlowers = 0;
// Fills the list with the cows attributes (time and flowers destroyed)
for (int i = 0; i < numOfCows; i++) {
int theTime = Integer.parseInt(input.next());
int theFlowers = Integer.parseInt(input.next());
final Cow theCow = new Cow(theTime, theFlowers);
list.add(theCow);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
for (int k = 0; k < list.get(i).time; k++)
for (int j = i + 1; j < list.size(); j++) {
totalFlowers += (list.get(j).flowers * 2);
}
}
System.out.println(totalFlowers);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
input.close();
}
public static final class Cow implements Comparable<Cow> {
public final int time;
public final int flowers;
public Cow(final int theTime, final int theFlowers) {
time = theTime;
flowers = theFlowers;
}
@Override
public int compareTo(Cow other) {
int compared = 1;
if (this.time < other.time) {
compared = -1;
} else {
if (this.flowers > other.flowers) {
compared = -1;
}
}
return compared;
}
@Override
public String toString() {
return String.format("Time:%d Flowers: %d", time, flowers);
}
}
}
采纳答案by Lone nebula
In the statement if (this.flowers > other.flowers)
you do not consider the fact that this.time
could still be greater than other.time
.
在声明中,if (this.flowers > other.flowers)
您没有考虑this.time
仍然可能大于的事实other.time
。
You do also not consider the case when time
and flowers
are equal to those of the other Cow
.
您也不考虑当time
和flowers
等于其他 时的情况Cow
。
I'd prefer doing something like this:
我更喜欢做这样的事情:
public int compareTo(Cow other) {
int compare = this.time - other.time;
if(compare == 0) {
compare = other.flower - this.flower;
}
return compare;
}
回答by Lone nebula
//Here is sorted List alphabetically with syncronized
//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
*
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
});
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/
// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}
}
}
class Employee {
String name;
Employee (String name) {
this.name = name;
}
}
回答by devang
Essentially, you want to compare flower count only if time count is same.
本质上,您只想在时间计数相同时比较花数。
public int compareTo(Cow other) {
int comparison = new Integer(this.time).compareTo(new Integer(other.time));
if (comparison == 0) {
return (-1) * new Integer(this.flowers).compareTo(new Integer(other.flowers));
}
return comparison;
}