Java how to make arraylist character

Java how to make arraylist character

To create an ArrayList of characters in Java, you can use the ArrayList class and the Character class from the java.lang package.

Here is an example of how you can create an ArrayList of characters in Java:

refer to‮tual:‬turi.com
import java.util.ArrayList;
import java.lang.Character;

ArrayList<Character> list = new ArrayList<>();

list.add(Character.valueOf('a'));
list.add(Character.valueOf('b'));
list.add(Character.valueOf('c'));

System.out.println(list); // prints "[a, b, c]"

In this example, the ArrayList is created using the Character class as the type parameter. The add method is used to add characters to the list.

You can also use the Character class to convert a string to an ArrayList of characters, as shown in the following example:

import java.util.ArrayList;
import java.lang.Character;

String str = "abc";
ArrayList<Character> list = new ArrayList<>();

for (char c : str.toCharArray()) {
    list.add(Character.valueOf(c));
}

System.out.println(list); // prints "[a, b, c]"

In this example, the toCharArray method is used to convert the str string to an array of characters, and the for loop is used to iterate over the array and add each character to the list using the add method.

You can also use the CharSequence interface and the toString method to convert a string to an ArrayList of characters, as shown in the following example:

import java.util.ArrayList;
import java.lang.Character;

String str = "abc";
ArrayList<Character> list = new ArrayList<>();

CharSequence cs = str;

for (int i = 0; i < cs.length(); i++) {
    list.add(Character.valueOf(cs.charAt(i)));
}

System.out.println(list); // prints "[a, b, c]"

In this example, the CharSequence interface is implemented by the String class, so the str string can be cast to a CharSequence object. The length method is used to get the length of the CharSequence, and the charAt method is used to get the character at a specific index. The for loop is used to iterate over the CharSequence and add each character to the list using the add method.

Created Time:2017-11-03 23:27:10  Author:lautturi