1

I am new to Java and trying to learn conversion from char ArrayList to char array. I am having some hard time to convert this.

 List<Character> code = new ArrayList<Character>();
 code.add("A");
 code.add("B");
 code.add("C");

This will display as [A, B, C]. What I want to do is to convert this array list to char[] array.

What I tried was the following:

char[] list = null;
for(int i=0; i<code.size(); i++){
    list[i] = code.get(i);
    System.out.println(list[i]); // this has the error
}

The error I am getting is java.lang.NullPointerException. I searched online but I couldn't find a "better" solution. Most of them are a conversion from string to char or vice versa. Perhaps I am missing some important knowledge about this. Again, I am new to Java and any help will be appreciated!.

3
  • 3
    The List interface includes a toArray method that does this conversion for you. Also, be careful about the difference between single and double quotes. Commented Apr 24, 2018 at 4:18
  • 1
    you should refer geeksforgeeks.org/… Commented Apr 24, 2018 at 4:28
  • double quotes are wrong. It's supposed to be single. Thanks for this. Commented Apr 24, 2018 at 4:34

3 Answers 3

1

You are getting a null pointer exception because you initialized the char array to null. Instead, you would want to initialize it to a new char array size equal to that of the ArrayList like:

char[] list = new char[code.size()];

Here is how all the code would look.

List<Character> code = new ArrayList<Character>();
code.add("A");
code.add("B");
code.add("C");


char[] list = new char[code.size()]; // Updated code

for(int i=0; i<code.size(); i++){
    list[i] = code.get(i);
    System.out.println(list[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this. Null Pointer exception is due to initializing to null

  List<Character> code = new ArrayList<Character>();
        code.add('A');
        code.add('B');
        code.add('C');


        Character[] arr = new Character[code.size()];
        arr = code.toArray(arr);

        System.out.println(arr);

Comments

0

Initialize the char[] before using. something like

char[] list = new char[code.size()];

You are getting NullPointerException since the list variable is initialised with null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.