Home > Back-end >  Passing an array to a variable that has a different type in Java
Passing an array to a variable that has a different type in Java

Time:12-02

I have a class InQueue with the following:

static Queue<String> q = null;

public InQueue(String[] input){
    q = new LinkedList<String>();

}
public static Queue<String> newInputQueue(String[] inputArray){
    q.addAll(Arrays.asList(inputArray));
    q.add("$");
    return q;
}

And I have an array in main that I'm trying to do this:

String[] inputArr = {"id", " ", "id", "*", "id"};
InQueue inQueue = new InQueue(inputArr);

I want to pass inputArr to inQueue so that my array goes into the queue. But obviously I can't do that because the InQueue constructor doesn't have parameters. Is there a way to do this? I've tried various ways and most of them either don't work, or they return an empty queue.

CodePudding user response:

You can simply create that constructor yourself:

public InQueue(String[] arr){
    q = new LinkedList<String>(Arrays.asList(arr));
}

You should also remove the static keyword from both the field q as well as the newInputQueue method, is there a reason for it?

CodePudding user response:

Change your class to something like this:

private Queue<String> q = null;

private InQueue(){
    q = new LinkedList<String>();    
}
public static InQueue newInputQueue(String[] inputArray){
    InQueue res = new InQueue();
    res.q.addAll(Arrays.asList(inputArray));
    res.q.add("$");
    return res;
}

What are the main differences between this and your code ? The first is the lack of the static on the data member. static there means that object is "static" (kind of unique/shared) for all instances of your class. Get rid of it to avoid future headaches.

The constructor has become private, this tells any user, there should be an alternative way to construct the object.

The alternative way to construct the object is the static function, which can invoke the private constructor (because they're in the same classe) and can access any datamember of the class itself.

Now whenever you need to allocate an InQueue, you just use the static factory.

InQueue myQueue = InQueue.newInputQueue(someArray);

CodePudding user response:

Easiest way is to add another constructor to your InQueue class that converts the array to a LinkedList. Something like:

public InQueue(String[] inputArr) {
  q = new LinkedList<> (Arrays.asList(inputArr));
}

Alternatively, you can use the method you already have and reassign like:

String[] inputArr = {"id", " ", "id", "*", "id"};
InQueue inQueue = new InQueue();
inQueue = inQueue.newInputQueue(inputArr);
  • Related