I am trying to create a method that creates new LinkedLists
. I want to pass a String
parameter to use as the new LinkedList
identifier but I'm getting an error "java: variable s is already defined in method createQueue(java.lang.String)
"
Is there anyway to use a String
to create the new LinkedList
like this?
I need to do it this way for an assignment so I can't change the method declaration.
public void createQueue(String s){
LinkedList<obj> s = new LinkedList<obj>();
}
I may be looking at this the wrong way also. I'm just trying to create the linkedList atm. But my requirements are as follows:
boolean addQueue(String)
This method will have a String parameter. It will return a boolean. It will add a new queue specified by the parameter. E.g. addQueue(“ready”) would create a new queue called “ready” to the list of queues. If there is already a queue by the specified name, then this method will return false. E.g. If you already have a queue named “ready” and you call addQueue(“ready”), it will return false. Otherwise, it will create the queue and return true.
You have to maintain a collection of queues. Because each queue has a unique name, the most appropriate collection is 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;
}
}
}
Here I made the assumption that the queue is implemented with an ArrayList
, but of course LinkedList
would work similarly. Then the method addPcb()
is quite obvious:
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);
}
}
An alternative implementation of addPcb()
, using addQueue()
could be:
public void addPcb(Pcb pcb, String queueName) {
addQueue(queueName);
List<Pcb> queue = queues.get(queueName);
queue.add(pcb);
}