我正在将字符串递归转换为Character ArrayList。每次调用该函数时都会创建一个新的ArrayList。
public static ArrayList<Character> strToList(String word)
{
ArrayList<Character> letters = new ArrayList<Character>();
//ArrayList<Character> emptyList = new ArrayList<Character>();
if(word.isEmpty() == true){
return letters;
}
else {
char let = word.charAt(0);
letters.add(Character.valueOf(let));
System.out.println(letters);
String temp = word.substring(1, word.length());
System.out.println(temp);
return strToList(temp);
}
}
答案 0 :(得分:2)
将单个ArrayList
实例作为参数传递给您的方法(public static void strToList(String word, List<Character> letters)
-这种情况下您的方法不必返回任何内容),或将ArrayList
实例合并为如下:
public static ArrayList<Character> strToList(String word)
{
ArrayList<Character> letters = new ArrayList<Character>();
if (!word.isEmpty()) {
char let = word.charAt(0);
letters.add(Character.valueOf(let));
System.out.println(letters);
String temp = word.substring(1, word.length());
System.out.println(temp);
letters.addAll(strToList(temp)); // add all the elements of the List returned by the
// recursive call to the new List created in this
// call
}
return letters;
}
答案 1 :(得分:1)
如下更新代码
public static ArrayList<Character> strToList(String word, ArrayList<Character> letters)
{
// ArrayList<Character> letters = new ArrayList<Character>();
//ArrayList<Character> emptyList = new ArrayList<Character>();
if(word.isEmpty() == true){
return letters;
}
else {
char let = word.charAt(0);
letters.add(Character.valueOf(let));
System.out.println(letters);
String temp = word.substring(1, word.length());
System.out.println(temp);
return strToList(temp, letters);
}
}
public static void main(String[] args) throws Exception {
ArrayList<Character> letters = new ArrayList<Character>();
System.out.println(strToList("Hello", letters)); // [H, e, l, l, o]
}
在递归中,您需要注意变量的范围。
在您的帖子中,由于要在每个调用堆栈上创建新的ArrayList,因此它没有来自先前调用堆栈的数据。
因此,为了传递列表数据,我将其作为函数的参数传递。这将保留所有调用堆栈中的所有数据。
答案 2 :(得分:0)
您也可以通过这种方式
public static ArrayList<Character> strToCharList(String word) {
ArrayList<Character> letters = new ArrayList<Character>();
if (word.isEmpty() == true)
return letters;
else
return (ArrayList<Character>) word.chars().mapToObj(character -> (char) character).collect(Collectors.toList());
}
或
public static ArrayList<Character> strToCharList(String word) {
return (word != null)? (ArrayList<Character>) word.chars().mapToObj(character -> (char) character).collect(Collectors.toList()): new ArrayList<Character>();
}
方法调用
public static void main(String[] args) {
System.out.println(strToList("Hello"));
}
输出:
[H, e, l, l, o]