Java 字符对象的 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24718563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ArrayList of Character Objects
提问by user3806226
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.
我想根据一串字母中的字符创建一个字符对象的 ArrayList。但是,我似乎无法弄清楚如何填充该 ArrayList 以匹配字符串。我一直试图让它遍历字符串,以便稍后,如果我更改字符串的内容,它会进行调整。无论如何,无论我做什么,我都会遇到某种语法错误。
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));
}
}
采纳答案by Tony
In your case, words.charAt()
is enough.
在你的情况下,words.charAt()
就足够了。
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