I have this array that I converted into a list:
String[] inputArr = {"id", "+", "id", "*", "id"}; List<String> inputList = Arrays.asList(inputArr);
How would I go about adding a character to the end of the list since there isn’t a specific add function for Lists?
Edit: Both my classes and code
import java.util.*; public class Main{ public static void main(String[] args) { String[] inputArr = {"id", "+", "id", "*", "id"}; //InQueue inQueue = new InQueue(inputArr); InQueue inQueue = new InQueue(); } } import java.util.*; public class InQueue { public static String[] inputArr = {"id", "+", "id", "*", "id"}; public static List<String> inputList = Arrays.asList(inputArr); }
Advertisement
Answer
you have an array of
String
and convert it toList
ofString
so you cannot add achar
to it.When you do
Arrays.asList
you getjava.util.Arrays.ArrayList
(which is not ajava.util.ArrayList
). The former has notadd
function implemented, so you cannot add anything there.You can construct a “normal” list (
java.util.ArrayList
) using what you currently have as a constructor parameter.
N.B. you won’t be able to add a
char
but you can add aString
So that the final solution would be:
String[] inputArr = {"id", "+", "id", "*", "id"}; List<String> inputList = new ArrayList<>(Arrays.asList(inputArr)); inputList.add("$");
Probably you want to achieve something like this:
import java.util.*; class Main{ public static void main(String[] args) { String[] inputArr = {"id", "+", "id", "*", "id"}; InQueue inQueue = new InQueue(inputArr); inQueue.printQueue(); } } class InQueue { List<String> tokens; public InQueue(String[] input){ tokens = new ArrayList<>(Arrays.asList(input)); tokens.add("$"); } public void printQueue(){ System.out.println(tokens); } }