Home > Software engineering >  Adding an element to the end of a List in java
Adding an element to the end of a List in java

Time:11-27

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);
}

CodePudding user response:

  1. you have an array of String and convert it to List of String so you cannot add a char to it.

  2. When you do Arrays.asList you get java.util.Arrays.ArrayList (which is not a java.util.ArrayList). The former has not add function implemented, so you cannot add anything there.

  3. 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 a String

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);
    }
}
  • Related