Reputation: 235
I want to create an ArrayList of character objects based off the characters in a string of letters. But, I can't seem to figure out how to fill that ArrayList to match the String. I've been trying to have it iterate through the string so that later, if I change the content of the string it'll adjust. Regardless, no matter what I do I'm getting some sort of syntax error.
Could anybody please guide me in the right direction? Thanks a bunch!
import java.util.ArrayList;
import java.text.CharacterIterator; //not sure if this is necessary??
public class Test{
//main method
String words = new String("HELLO GOODBYE!");
ArrayList<Character> sample = new ArrayList<Character>();
for(int i = 0; i<words.length(); i++){
sample.add((char)Character.codePointAt(sample,i));
}
}
Upvotes: 10
Views: 117647
Reputation: 52366
This code adds all the characters in a character array to an ArrayList
.
Character[] letters = {'a', 'b', 'c', ...};
List<Character> array = new ArrayList<Character>();
array.addAll(Arrays.asList(letters));
Upvotes: 1
Reputation: 6148
In your case, words.charAt()
is enough.
import java.util.ArrayList;
public class Test{
String words = new String("HELLO GOODBYE!");
ArrayList<Character> sample = new ArrayList<Character>();
for(int i = 0; i<words.length(); i++){
sample.add(words.charAt(i));
}
}
Read more: Stirng, Autoboxing
Upvotes: 16