如何创建方法来生成新的 LinkedList?
How can I create method to generate new LinkedList?
我正在尝试创建一个创建新 LinkedLists
的方法。我想传递一个 String
参数以用作新的 LinkedList
标识符,但出现错误“java: variable s is already defined in method createQueue(java.lang.String)
”
有没有办法像这样使用 String
来创建新的 LinkedList
?
我需要以这种方式进行分配,所以我无法更改方法声明。
public void createQueue(String s){
LinkedList<obj> s = new LinkedList<obj>();
}
我也可能看错了。我只是想创建 linkedList atm。但我的要求如下:
布尔添加队列(字符串)
此方法将有一个字符串参数。它将 return 一个布尔值。
它将添加一个由参数指定的新队列。例如。 addQueue(“ready”) 会在队列列表中创建一个名为“ready”的新队列。如果指定名称的队列已经存在,则此方法将为 return false。例如。如果您已经有一个名为“ready”的队列并且您调用 addQueue(“ready”),它将 return false。否则,它将创建队列并且 return true.
问题是您有两个不同的变量名为 s
- String s
参数(这是一个变量)和 LinkedList<obj> s
.
只需重命名其中一个即可。
您必须维护队列集合。因为每个队列都有一个唯一的名字,所以最合适的集合是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);
}
}
addPcb()
的替代实现,使用 addQueue()
可以是:
public void addPcb(Pcb pcb, String queueName) {
addQueue(queueName);
List<Pcb> queue = queues.get(queueName);
queue.add(pcb);
}
我正在尝试创建一个创建新 LinkedLists
的方法。我想传递一个 String
参数以用作新的 LinkedList
标识符,但出现错误“java: variable s is already defined in method createQueue(java.lang.String)
”
有没有办法像这样使用 String
来创建新的 LinkedList
?
我需要以这种方式进行分配,所以我无法更改方法声明。
public void createQueue(String s){
LinkedList<obj> s = new LinkedList<obj>();
}
我也可能看错了。我只是想创建 linkedList atm。但我的要求如下:
布尔添加队列(字符串)
此方法将有一个字符串参数。它将 return 一个布尔值。 它将添加一个由参数指定的新队列。例如。 addQueue(“ready”) 会在队列列表中创建一个名为“ready”的新队列。如果指定名称的队列已经存在,则此方法将为 return false。例如。如果您已经有一个名为“ready”的队列并且您调用 addQueue(“ready”),它将 return false。否则,它将创建队列并且 return true.
问题是您有两个不同的变量名为 s
- String s
参数(这是一个变量)和 LinkedList<obj> s
.
只需重命名其中一个即可。
您必须维护队列集合。因为每个队列都有一个唯一的名字,所以最合适的集合是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);
}
}
addPcb()
的替代实现,使用 addQueue()
可以是:
public void addPcb(Pcb pcb, String queueName) {
addQueue(queueName);
List<Pcb> queue = queues.get(queueName);
queue.add(pcb);
}