LinkedList的Collections.sort()无效

时间:2017-11-20 14:59:36

标签: java sorting

我正在尝试根据LinkedList优先级

Attribute进行排序

航班等级

/**
 * @author Dylan
 *
 */

/**
 * A Class to hold information for flights and allow it to be manipulated
 *
 */
public class Flight {
    private String flightID;//FlightId eg(BA001)
    Integer priority; // 1 = lowest | 9 = highest

    /**
     * A simple constructor to initialise sensible values to attributes
     */
    public Flight() {
        this.setFlightID("BA378"); //initialises the attributes to sensible values
        this.setPriority(1); //initialises the attributes to sensible values
    }
    /**
     * A param constrctor to initials attributes to values of params
     * @param flightID
     * @param priority
     */
    public Flight(String flightID, Integer priority) {
        this.flightID = flightID; // Initialises flightID to the value of the param
        this.priority = priority;// initialises priority to the value of the param
    }

    /**
     * A simple method to return the flightID
     * @return
     */
    public String getFlightID() {
        return flightID; //returns flightID
    }

    /**
     * A simple method to set the flightID
     * @param flightID
     */
    public void setFlightID(String flightID) {
        this.flightID = flightID; //sets value of flightID to params
    }

    /**
     * a simple method to return the priority of the flight
     * @return
     */
    public Integer getPriority() {
        return priority;//returns priority of the flight
    }

    /**
     * a simple method to set the priority of the flight
     * @param priority
     */
    public void setPriority(int priority) {
        this.priority = priority;//sets the flight priority to value of params
    }
    /**
     * A method to turn attributes into a sensible string
     */
    public String toString() {
        return "Flight [flightID=  " + flightID + ", priority=" + priority + "]";//toString to change attributes into a string that's easy to read
    }
}

PriorityFlightQueue1 Class

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;

public class PriorityFlightQueue1 extends AbstractFlightQueue implements Comparator<Flight> {
    LinkedList<Object> flights = new LinkedList<Object>();

    public void joinQueue(Flight f) {
        flights.addLast(f);

    }

    public Object landFlight() {
        return flights.removeFirst();
    }

    public int size() {
        return flights.size();
    }

    public void clear() {
        Iterator<Object> it = flights.iterator();//Initialise iterator to it
        while(it.hasNext()) {//A While loop to check if there's another index after the current index
            flights.removeFirst();//If the condition is true then it will remove index
        }
    }

    public void display() {
        for(Object f : flights) {//for each statement
        System.out.println(f);//prints out f to console
        }

    }

    public int compare(Flight f1, Flight f2) {
        if(f1.getPriority() < f2.getPriority()){
            return 1;
        } else {
            return -1;
        }
}
}

来自FlightTestClass的方法,这基本上将数据放入链表中。我正在尝试使用Collections.sort()对数据进行排序,如下所示

public void testPriorityFlightQueue1() {
        PriorityFlightQueue1    q = new PriorityFlightQueue1();

        Flight f1 = new Flight("BA001", 3);//entering flight details into the linkedlist(queue)
        Flight f2 = new Flight("NR273", 7);//entering flight details into the linkedlist(queue)
        Flight f3 = new Flight("RA291", 1);//entering flight details into the linkedlist(queue)
        Flight fref;


        showPriorityFlightQueue1(q);
        q.joinQueue(f1);
        System.out.println(f1 + " has joined the queue to land");
        showPriorityFlightQueue1(q);
        q.joinQueue(f2);
        System.out.println(f2 + " has joined the to land");
        showPriorityFlightQueue1(q);
        q.joinQueue(f3);
        System.out.println(f3 + " has joined the to land");
        showPriorityFlightQueue1(q);
        System.out.println("\n-----------------------------------------\n");    
        fref = (Flight) q.landFlight();
        System.out.println(fref + " has landed");
        showPriorityFlightQueue1(q);
        fref = (Flight) q.landFlight();
        System.out.println(fref + " has landed");
        showPriorityFlightQueue1(q);
        fref = (Flight) q.landFlight();
        System.out.println(fref + " has landed");
        showPriorityFlightQueue1(q);
        System.out.println("\n-----------------------------------------\n");

        Collections.sort(q.flights);

        showPriorityFlightQueue1(q);


    }

我真的不确定为什么它不会对LinkedList进行排序 在Eclipse中,建议框显示:

  

类型集合中的方法sort(List)不适用于参数(LinkedList)

然后它要我将参数q.flights投射到List<T>

3 个答案:

答案 0 :(得分:2)

创建Flight比较器

public class Flight {
    private String flightID; // FlightId eg(BA001)
    Integer priority; // 1 = lowest | 9 = highest

    public static final Comparator<Flight> SORT_MAX_PRIORITY = new Comparator<Flight>() {
        @Override public int compare(Flight a, Flight b) {
            return b.priority - a.priority;
        }
    };

    public static final Comparator<Flight> SORT_MIN_PRIORITY = new Comparator<Flight>() {
        @Override public int compare(Flight a, Flight b) {
            return a.priority - b.priority;
        }
    };

    public static final Comparator<Flight> SORT_BY_ID = new Comparator<Flight>() {
        @Override public int compare(Flight a, Flight b) {
            return a.flightID.compareTo(b.flightID);
        }
    };
    // the rest of the class...
}

然后使用其中一个进行排序。

Collections.sort(q.flights, Flight.SORT_MAX_PRIORITY);

答案 1 :(得分:1)

分析

目前,您正在尝试调用该方法:

static <T extends Comparable<? super T>>
void sort(List<T> list)

LinkedList<Object> flights为参数。

请注意,Object类未实现Comparable<? super Object>接口。所以,这就是编译失败的原因。

解决方案概述

鉴于,我们有一个名为Entity的小组。

实现类的比较操作有两种不同的方法:

  1. «内部»比较(参见the «Comparable type» section):单个比较操作由实体本身实现:Entity类实现Comparable<? super Entity>接口。要使用此比较操作,必须调用方法:

      

    public static <T extends Comparable<? super T>> void sort(List<T> list)

         

    根据元素的自然顺序,将指定列表按升序排序。列表中的所有元素都必须实现Comparable接口。此外,列表中的所有元素必须具有可比性(即e1.compareTo(e2)不得为列表中的任何元素ClassCastExceptione1抛出e2

         

    - public static <T extends Comparable<? super T>> void Collections.sort(List<T> list) (Java Platform SE 8)

  2. «外部»比较(参见the «Comparators» section):从一对多的比较操作实现为实体比较器类 - 实现Comparator<? super Entity>接口的类。要使用此比较操作,必须调用方法:

      

    public static <T> void sort(List<T> list, Comparator<? super T> c)

         

    根据指定比较器引发的顺序对指定列表进行排序。列表中的所有元素必须使用指定的比较器进行相互比较(即,c.compare(e1, e2)不得为列表中的任何元素ClassCastExceptione1抛出e2

         

    - public static <T> void Collections.sort(List<T> list, Comparator<? super T> c) (Java Platform SE 8)

  3. 这些方法可以合并,即它们不是相互排斥的。

    最小解决方案

    目前,您已经定义了唯一一种比较Flight类实例的方法,这种比较不需要任何外部上下文(只是Flight类本身的实例),因此,最小的解决方案是使Flight类具有可比性。

    1. 使用具体的(LinkedList<Object> flights)代替“过于通用”的航班集合(LinkedList<Flight> flights)。
    2. 不要将PriorityFlightQueue1类作为Comparator<Flight>接口实现,而是通过在此处移动比较来更新Flight类的实现以实现Comparable<Flight>接口。 / LI>

      参考文献:

      1. Object Ordering (The Java™ Tutorials > Collections > Interfaces), Oracle, The Java™ Tutorials

答案 2 :(得分:1)

据我所知,这是一项研究任务。有很多可以用命名,类型转换和格式化来批评。没有冒犯,只需记住未来的风格改进。至少 - 请不要将//comments添加到行尾,让它成为单行评论。

关于这个问题:

Collections.sort(q.flights)要求q.flights是可比较的东西的集合。但在你的情况下,这是List<Objects>。您的Objects确实是Flights并不重要。列表定义为List<Objects>。而Object不是Comparable。即使您有List<Flight>,您的Flights也不是Comparable

选项1.将您的航班设为Flight implements Comparable<? super Flight>,并将您的列表定义为List<SomethingComparable super Flight>

选项2.如果要对未实现Comparable的任何内容进行排序,可以使用其他排序方法:

Collections.sort(List<Something> list, Comparator<? super Something>)

如果您的列表不是PriorityFlightQueue1Comparator<Flight>可以List<Object>传递到那里。