使用Comparable接口对ArrayList进行排序

时间:2013-04-28 22:53:32

标签: java sorting object arraylist comparable

我正在完成一项任务。我有我需要做的基础知识,但由于某种原因,compareTo没有在一组示例输入上正确排序。第一组输入正确排序并返回正确的值,但第二组重新排列,但不排序。基本上我有一个对象牛,有一个时间和一些花吃。我想把这些物品和它们分类,首先是时间,先是最短时间,然后是吃花,最大量先吃。所以,如果我有3头奶牛,1和10,2和5,2和7.我会排序他们,第一,第三和第二。希望这是有道理的。我不确定为什么Collection.sort没有按预期工作......但希望有人能引导我朝着正确的方向前进。

到目前为止,这是我的代码:

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);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

if (this.flowers > other.flowers)语句中,您并未考虑this.time仍然可能大于other.time的事实。

timeflowers与其他Cow相同时,您也不会考虑这种情况。

我更喜欢做这样的事情:

public int compareTo(Cow other) {
    int compare = this.time - other.time;
    if(compare == 0) {
        compare = other.flower - this.flower;
    }
    return compare;
}

答案 1 :(得分:0)

基本上,只有在时间计数相同时才想要比较花数。

    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;
    }

答案 2 :(得分:0)

//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;

}
}