[英]Sort an arraylist of objects in java
我正在創建一些不同的CPU調度算法的模擬,並且還想同時學習一種新語言。 我遇到的麻煩是試圖根據進程的到達時間對進程的數組列表進行排序。 我遇到的錯誤是沒有為Collections.sort(processes)找到合適的方法,而且我不太確定該怎么做。
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
public interface Comparable
{
int compareTo(Object otherObject);
}
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);
}
}
您需要實現java.lang.Comparable
。 編寫自己的文件將不起作用,因為它在另一個程序包中。
因此,只需為您的Process類添加import聲明,然后刪除您自己的Comparable接口。 (+請參閱第一個評論)
您可以創建一個自定義的Comperator,它將根據到達時間比較兩個Process對象。 Collections類具有一個重載的sort()方法,該方法接受一個集合(列表,數組)和一個Comperator。
這是一個很好的例子:
http://www.javadeveloper.co.in/java-example/java-comparator-example.html
請同時參閱Sibbo的回復。
我已經創建了一個函數,用於根據模型類中的特定變量對對象列表進行排序。 它可能與您所需的不完全匹配,但是您可以接受這個想法。 我正在使用反射來對具有任何數據類型的任何類模型進行排序。
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;
}
您可以像這樣簡單地調用該函數:
Vector sortedList=sort(UnsortedList, "bean.Items", "getItemName", "asc");
此行將根據商品名稱升序對我的商品列表(商品是模型類)進行排序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.