简体   繁体   English

在Java中对对象的数组列表进行排序

[英]Sort an arraylist of objects in java

I'm working on creating a simulating of some different CPU scheduling algorithms and also wanted to learn a new language at the same time. 我正在创建一些不同的CPU调度算法的模拟,并且还想同时学习一种新语言。 The trouble I'm running into is trying to sort an arraylist of processes based on their arrival time. 我遇到的麻烦是试图根据进程的到达时间对进程的数组列表进行排序。 The error I'm running into is that there is no suitable method found for Collections.sort(processes), and I'm not really sure what to do. 我遇到的错误是没有为Collections.sort(processes)找到合适的方法,而且我不太确定该怎么做。

Process.java Process.java

import java.util.Random;
public class Process implements Comparable
{

    private Random generator;
    private String name;
    private int burstTime;
    private int priority;
    private int arrivalTime;

    /**
     * Process constructor where the user choose the values
     * @param nameValue name of the process
     * @param burstTimeValue burst time of the process
     * @param priorityValue priority of the process
     * @param arrivalTimeValue arrival time of the process
     */
    public Process(String nameValue, int burstTimeValue, int priorityValue,
            int arrivalTimeValue)
    {
        name = nameValue;
        burstTime = burstTimeValue;
        priority = priorityValue;
        arrivalTime = arrivalTimeValue;
    }

    /**
     * Process constructor that randomizes the values of
     * name, burst time, priority, and arrival time.
     */
    public Process()
    {
        generator = new Random();
        name = "Process" + generator.nextInt(10000);
        burstTime = generator.nextInt(10);
        priority = generator.nextInt(5);
        arrivalTime = generator.nextInt(30);
    }

    /**
     * Returns the name of the process
     * @return name the name of the process
     */
    public String getName()
    {
        return name;
    }

    /**
     * Sets the name of the process
     * @param aValue value to set the process name to
     */
    public void setName(String aValue)
    {
        name = aValue;
    }

    /**
     * Returns the burst time of the process
     * @return burstTime the burst time of the process
     */
    public int getBurstTime()
    {
        return burstTime;
    }

    /**
     * Sets the burst time of a process
     * @param aValue the value for the burst time of a process
     */
    public void setBurstTime(int aValue)
    {
        burstTime = aValue;
    }

    /**
     * Returns the priority value of the process
     * @return priority the priority of the process
     */
    public int getPriority()
    {
        return priority;
    }

    /**
     * Sets the priority of a process
     * @param aValue value for priority
     */
    public void setPriority(int aValue)
    {
        priority = aValue;
    }

    /**
     * Returns the arrival time of the process
     * @return arrival time the arrival time of the process
     */
    public int getArrivalTime()
    {
        return arrivalTime;
    }

    /**
     * Sets the arrival time value
     * @param aValue value for arrival time
     */
    public void setArrivalTime(int aValue)
    {
        arrivalTime = aValue;
    }

    /**
     * Overrides the toString method from the String class
     * Returns a printout of the object's variables
     * @return printout of the object's variables
     */
    @Override
    public String toString()
    {
        return "Process[name=" + name + " bTime=" + burstTime
                + " priority=" + priority + " aTime=" + arrivalTime +"]";
    }

    /**
     * Compares two process objects
     * @param otherObject another process object
     * @return the order of two processes
     */
    @Override
    public int compareTo(Object otherObject)
    {
        Process other = (Process) otherObject;
        if (arrivalTime < other.arrivalTime) return -1;
        if (arrivalTime == other.arrivalTime) return 0;
        return 1;
    } 
}

Comparable.java Comparable.java

public interface Comparable
{
    int compareTo(Object otherObject);
}

Cpu.java Cpu.java

import java.util.ArrayList;
import java.util.Collections;
public class Cpu implements
{
    private ArrayList<Process> processes;

    /**
     * 
     */
    public Cpu()
    {
        processes = new ArrayList<Process>();
    }

    /**
     * Adds a process to the ArrayList
     * @param p the process that is being added
     */
    public void addProcess(Process p)
    {
        processes.add(p);
    }

    public void sort()
    {
        Collections.sort(processes);
    }      
}

You need to implement java.lang.Comparable . 您需要实现java.lang.Comparable Writing your own won't work, because it's in another package. 编写自己的文件将不起作用,因为它在另一个程序包中。

So just add the import declaration in for your Process class and delete your self made Comparable interface. 因此,只需为您的Process类添加import声明,然后删除您自己的Comparable接口。 (+ see first comment) (+请参阅第一个评论)

You can create a custom Comperator which will compare two Process objects based on the arrival time. 您可以创建一个自定义的Comperator,它将根据到达时间比较两个Process对象。 Collections class has an overloaded sort() method that takes a collection (list, array) and a Comperator. Collections类具有一个重载的sort()方法,该方法接受一个集合(列表,数组)和一个Comperator。

Here is an excellent example for doing so: 这是一个很好的例子:

http://www.javadeveloper.co.in/java-example/java-comparator-example.html http://www.javadeveloper.co.in/java-example/java-comparator-example.html

Please see Sibbo's response as well. 请同时参阅Sibbo的回复。

I've made ​​a function to sort a list of objects by a specific variable in the model class. 我已经创建了一个函数,用于根据模型类中的特定变量对对象列表进行排序。 It may not directly match the one you need, but maybe you can take the idea. 它可能与您所需的不完全匹配,但是您可以接受这个想法。 I'm using reflection to be able to sort any class models with any data type. 我正在使用反射来对具有任何数据类型的任何类模型进行排序。

 public Vector sort(Vector list, String kelas, String s, String asc) throws NoSuchMethodException {

        try {
            // Creates an object of type Class which contains the information of
            // the class String
            Object[] obj = list.toArray();
            Object[] args = {};
            Class cl = Class.forName(kelas);
            Method toSort = cl.getMethod(s, null);
            if (asc.equalsIgnoreCase("desc")) {
                if (toSort.getReturnType().toString().equalsIgnoreCase("int") || toSort.getReturnType().toString().equalsIgnoreCase("double")) {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (Double.parseDouble(toSort.invoke(obj[i], args).toString()) < Double.parseDouble(toSort.invoke(obj[j], args).toString())) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (toSort.invoke(obj[i], args).toString().compareToIgnoreCase(toSort.invoke(obj[j], args).toString()) < 0) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            } else {
                if (toSort.getReturnType().toString().equalsIgnoreCase("int") || toSort.getReturnType().toString().equalsIgnoreCase("double")) {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (Double.parseDouble(toSort.invoke(obj[i], args).toString()) > Double.parseDouble(toSort.invoke(obj[j], args).toString())) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < obj.length; i++) {
                        for (int j = i; j < obj.length; j++) {
                            try {
                                if (toSort.invoke(obj[i], args).toString().compareToIgnoreCase(toSort.invoke(obj[j], args).toString()) > 0) {
                                    Object temp = obj[i];
                                    obj[i] = obj[j];
                                    obj[j] = temp;
                                }
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalArgumentException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InvocationTargetException ex) {
                                Logger.getLogger(DbBean.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            }

            list = new Vector();
            for (int i = 0; i < obj.length; i++) {
                list.add(obj[i]);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

you can call that function as simple as this : 您可以像这样简单地调用该函数:

Vector sortedList=sort(UnsortedList, "bean.Items", "getItemName", "asc");

This line will sort my item list (item is a model class) based on Item Name ascending 此行将根据商品名称升序对我的商品列表(商品是模型类)进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM