【发布时间】:2021-01-25 01:46:56
【问题描述】:
我有一个类 (ClassOne),它有一个实例类 (Process) 的列表,我试图弄清楚如何根据它们的优先级对它们进行排序。
public class ClassOne
{
static List<Process> processList = new ArrayList<Process>();
public static void main(String[] args)
{
//hardcoded for example
processList.add(new Process(3));
processList.add(new Process(1));
processList.add(new Process(2));
The processes are current not ordered in the List by priority, so I call insertion sort
}
//Im pretty sure this is changing their priority instead of where they are in the List, but i dont know how to change it
public static void InsertionSort()
{
int n = processList.size();
for (int i = 1; i < n; ++i)
{
int key = processList.get(i).priority;
int j = i - 1;
/* Move elements of processList.get(0..i-1]).priority, that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && processList.get(j).priority > key)
{
processList.get(j+1).priority = processList.get(j).priority;
j = j - 1;
}
processList.get(j + 1).priority = key;
}
}
public class Process
{
int priority;
public Process(int tempPriority)
{
priority = tempPriority;
}
}
任何排序方法都可以,我想按优先级从最小到最大对 processList 中的每个 Process 对象进行排序。
尝试第一个解决方案后的代码:
public static void InsertionSort()
{
System.out.println(processList.get(0).name);
System.out.println(processList.get(1).name);
int n = processList.size();
for (int i = 1; i < n; ++i)
{
int key = processList.get(i).priority;
int j = i - 1;
//The method set(int, Process) in the type List<Process> is not applicable for the arguments (int, int)
/* Move elements of processList.get(0..i-1]).priority, that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && processList.get(j).priority > key)
{
processList.set(j + 1, processList.get(j));
j = j - 1;
}
processList.set(j + 1, processList.get(i));
System.out.println("Queue Sorted");
System.out.println(processList.get(0).name);
System.out.println(processList.get(1).name);
}
【问题讨论】:
-
你试过看List的排序方法吗? docs.oracle.com/javase/8/docs/api/java/util/…