Reputation: 3057
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!.
Upvotes: 1
Views: 1053
Reputation: 1592
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.
Upvotes: 0
Reputation: 1954
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);
Upvotes: 0
Reputation: 2432
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]);
}
Upvotes: 1