如何在java中将对象添加到ArrayList中
Posted
技术标签:
【中文标题】如何在java中将对象添加到ArrayList中【英文标题】:How to add an object into ArrayList in java 【发布时间】:2013-02-27 17:02:22 【问题描述】:这里有两个类,query sentence和stackov。一个arraylist用于存储查询语句类的对象。但是最近添加的对象覆盖了之前的对象。如何添加对象使其不被覆盖?
QuerySentence.java
public class QuerySentence
public static String query;
public static String label;
public QuerySentence()
public QuerySentence(String query,String label)
this.query = query;
this.label = label;
Stackov.java
package QueryClassifier;
import java.util.ArrayList;
public class stackov
public static void main(String args[])
QuerySentence qs1 = new QuerySentence("What state produces the best lobster to eat","LOCATION");
QuerySentence qs2 = new QuerySentence("What is Dick Clark's birthday","DATE");
ArrayList<Object> doclist = new ArrayList<Object>();
doclist.add(0,qs1);
doclist.add(1,qs2);
int size = doclist.size();
while(size>0)
QuerySentence qs3 = (QuerySentence) doclist.get(size-1);
System.out.println("\nin loop : " + qs3.label + qs3.query);
size--;
【问题讨论】:
尝试正确缩进你的代码。也不需要发布两个完整的课程,只需发布ArrayList
操作即可。
【参考方案1】:
doclist.add(qs1);
doclist.add(qs2);
【讨论】:
【参考方案2】:问题不是来自你的循环,而是来自你的班级QuerySentence
。您正在创建静态对象,这意味着您不会为类的不同实例创建不同的字段,但该类将只有它们的唯一副本。
所以这里发生了什么,您将这些值分配给您的班级QuerySentence
:
QuerySentence qs1 = new QuerySentence("What state produces the best lobster to eat","LOCATION");
然后用这个把它擦掉:
QuerySentence qs2 = new QuerySentence("What is Dick Clark's birthday","DATE");
当您将两个对象添加到您的ArrayList
中时,当然在您的循环中您将打印两个结果。但只有qs2中的结果。从您的字段声明中删除static
,它将正常工作:
public String query;
public String label;
添加时不需要为查询语句编制索引。
doclist.add(qs1);
doclist.add(qs2);
您还可以改进循环。你可以这样做:
ArrayList<QuerySentence> doclist = new ArrayList<QuerySentence>();
// some code...
for(QuerySentence q : doclist)
System.out.println("In loop : " + q.label + q.query);
还请记住 Java 约定:您的类应以大写字母 (Stackov
) 开头。如果您还从事封装工作,最好声明您的字段private
并为它们创建getters
和setters
。有了这个你的for-statement
应该是这样的:
for(QuerySentence q : doclist)
System.out.println("In loop : " + q.getLabel() + q.getQuery());
【讨论】:
for 循环显示错误 "for(QuerySentence q : doclist)" as "Type mismatch: cannot convert from element type Object to QuerySentence" 那是因为您已将 ArrayList 声明为ArrayList<Object> doclist = new ArrayList<Object>();
。请改用ArrayList<QuerySentence> doclist = new ArrayList<QuerySentence>();
。【参考方案3】:
索引不需要像这样添加
doclist.add(qs1);
doclist.add(qs2);
【讨论】:
【参考方案4】: public static void main(String args[])
QuerySentence qs1 = new QuerySentence("What state produces the best lobster to eat","LOCATION");
QuerySentence qs2 = new QuerySentence("What is Dick Clark's birthday","DATE");
ArrayList<QuerySentence> doclist = new ArrayList<QuerySentence>();
doclist.add(qs1);
doclist.add(qs2);
for(QuerySentence sent: docList)
System.out.println("\nin loop : " + sent.label + sent.query);
【讨论】:
以上是关于如何在java中将对象添加到ArrayList中的主要内容,如果未能解决你的问题,请参考以下文章