我正在尝试创建一个方法来创建新的LinkedLists
。我想传递一个 String
参数用作新的 LinkedList
标识符,但收到错误“java: 变量 s 已在方法 createQueue(java.lang.String)
中定义”
有没有办法像这样使用String
来创建新的LinkedList
?
我需要以这种方式进行分配,这样我就无法更改方法声明。
public void createQueue(String s){
LinkedList<obj> s = new LinkedList<obj>();
}
我可能也以错误的方式看待这个问题。我只是想创建 linkedList atm。但我的要求如下:
boolean addQueue(字符串)
此方法将有一个字符串参数。它将返回一个 boolean 值。 它将添加一个由参数指定的新队列。例如。 addQueue(“ready”) 会在队列列表中创建一个名为“ready”的新队列。如果已经存在指定名称的队列,则此方法将返回 false。例如。如果你已经有一个名为“ready”的队列,并且调用 addQueue(“ready”),它将返回 false。否则,它将创建队列并返回 true。
最佳答案
您必须维护队列集合。由于每个队列都有唯一的名称,因此最合适的集合是 Map
:
public class QueueManager {
private Map<String, List<Pcb>> queues = new HashMap<String, List<Pcb>>();
public boolean addQueue(String queueName) {
if (queues.containsKey(queueName)) {
// There is already a queue with that name
return false;
} else {
queues.put(queueName, new ArrayList<Pcb>());
return true;
}
}
}
这里我假设队列是用ArrayList
实现的,但是LinkedList
当然也会有类似的工作方式。那么方法addPcb()
就很明显了:
public void addPcb(Pcb pcb, String queueName) {
List<Pcb> queue = queues.get(queueName);
if (queue != null) {
queue.add(pcb);
} else {
throw new IllegalArgumentException("Queue does not exist: " + queueName);
}
}
使用 addQueue()
的 addPcb()
的替代实现可能是:
public void addPcb(Pcb pcb, String queueName) {
addQueue(queueName);
List<Pcb> queue = queues.get(queueName);
queue.add(pcb);
}
关于java - 如何创建方法来生成新的 LinkedList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634881/