Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing an array to a variable that has a different type in Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading