Java:如何在自定义ArrayList中添加字符串值

Java:如何在自定义ArrayList中添加字符串值,java,arraylist,Java,Arraylist,我想知道如何在自定义ArrayList中添加字符串值 我已经尝试了下面的代码,但它给了我错误 ArrayList<MyCustom> aList = new ArrayList<MyCustom>(); aList.add("My Name"); 假设您的类MyCustom和属性名称为: 您已经创建了一个列表,该列表将包含MyCustom类型的对象,因此除非您的对象扩展了字符串,否则无法向其中添加字符串 如果您想要一个包含String和MyCustom对象的列表,则必

我想知道如何在自定义ArrayList中添加字符串值

我已经尝试了下面的代码,但它给了我错误

ArrayList<MyCustom> aList = new ArrayList<MyCustom>();

aList.add("My Name");
假设您的类MyCustom和属性名称为:


您已经创建了一个列表,该列表将包含MyCustom类型的对象,因此除非您的对象扩展了字符串,否则无法向其中添加字符串

如果您想要一个包含String和MyCustom对象的列表,则必须按如下方式创建列表:

List<Object> list = new ArrayList<Object>();
list.add(new MyCustom(...));
list.add("Some String");

如前所述,MyCustom既不是String的子级,也不是String的父级,并且不能是。 这将使我们了解MyCustom对象的需要或您希望它执行的操作

通过使用下面的代码,可以将列表中的对象类型限制为Mycustom,这很好。但如果必须在该列表中添加字符串,则应删除这些类型。使用列表界面也是一种更好的做法

ArrayList<MyCustom> aList = new ArrayList<MyCustom>();
List aList = new ArrayList(); //This will allow all objects to be added to list.
或者,根据您对MyCustom对象的需要,您可以对其进行修改,以便按如下方式使用: aList.addnew MyCustomName字符串; 或
aList.addnew MyCustom.setNameName字符串

java中的ArrayList是泛型类型。意味着它可以存储任何对象。但要在ArrayList中存储对象,我们需要指定类名,这意味着ArrayList只存储您在声明数组列表时指定的类名

就你而言

ArrayList<MyCustom> aList = new ArrayList<MyCustom>();
您正在存储字符串值。String类和MyCustom类之间没有关系。所以java编译器会显示错误。要实现这一点,您需要实现

ArrayList<String> aList = new ArrayList<String>();

aList.add("My Name");
然后


字符串不扩展MyCustom,所以使用字符串代替MyCustom。顺便说一句,我很确定,MyCustom也不会扩展字符串,因为字符串是最终的。@Dmitry Ginzburg有其他选择吗?这取决于您想要实现什么。例如,您可以使用ArrayList,或者如果只包含字符串,则应使用ArrayList。我需要在ArrayList中的某个位置添加一个字符串。ArrayList允许以字符串是对象的形式添加字符串。使用原始类型是不好的,如果不是为了向后兼容,Java很可能会禁止使用。使用List and ArrayList而不是List andArrayList@KuluLimpa我知道我打字的时候忘了。谢谢
ArrayList<MyCustom> aList = new ArrayList<MyCustom>();
aList.add("My Name");
ArrayList<String> aList = new ArrayList<String>();

aList.add("My Name");
Class MyCustom {

String field;

public void setField(String f) {

field=f;
}

public String getField() {

return field;
}

}
ArrayList<MyCustom> aList = new ArrayList<MyCustom>();

aList.add(new MyCustom().setField("My Name"));