Java 无法向 Character ArrayList 添加字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24851012/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:13:01  来源:igfitidea点击:

Can't add chars to Character ArrayList

javastringarraylist

提问by user3807322

I'm having issues understanding ArrayList in Java. I tried to declare a Character ArrayList and add a char at 0, but it returned error at list.add(0, "B") line.

我在理解 Java 中的 ArrayList 时遇到问题。我试图声明一个 Character ArrayList 并在 0 处添加一个字符,但它在 list.add(0, "B") 行返回错误。

public class ArrListTest {
public static void main(String[] args) {
    ArrayList<Character> list;
    list.add(0, "B");
 }
}

Also I'm having issues reversing a string. Is there a way to reverse a string without using a loop?

另外我在反转字符串时遇到问题。有没有办法在不使用循环的情况下反转字符串?

采纳答案by Pshemo

"B"is instance of String, characters need to be surrounded with 'like 'B'.

"B"是 String 的实例,字符需要用'like包围'B'

use

list.add(0,'B');

If you want to add Bafter last element of list skip 0

如果要B在列表的最后一个元素后添加跳过0

list.add('B');

Also don't forget to actually initialize your list

也不要忘记实际初始化您的列表

List<Character> list = new ArrayList<>();
//                   ^^^^^^^^^^^^^^^^^^^

To know why I used List<Character> listas reference type instead of ArrayList<Character> listread:
What does it mean to “program to an interface”?

要知道为什么我使用List<Character> list引用类型而不是ArrayList<Character> list阅读:
“编程到接口”是什么意思?

回答by Reimeus

You're mixing up List.setwith List.add. Use a character literal instead of a Stringand use

List.setList.add. 使用字符文字代替 aString并使用

list.add('B');

after initializing the List

初始化后 List

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

回答by KARTHIK SARAGADAM

public static void main(String args[]) {

    ArrayList list= new ArrayList();
        list.add("B");

}

try this

尝试这个

回答by KARTHIK SARAGADAM

public class stackQuestions {

公共类堆栈问题{

public static void main(String args[]) {

    ArrayList list = new ArrayList();

    list.add("b");
    list.add(0, "a");// it will add to index 0
    list.add(0, "c");// it will replaces to index 0
    System.out.println(list);
}

}

}