如何在java中将对象添加到ArrayList中

时间:2013-03-12 08:56:14

标签: java oop arraylist

这是两个类,查询语句和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--;
                }

    }
}   

4 个答案:

答案 0 :(得分:7)

问题不是来自您的循环,而是来自您的班级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并为其创建getterssetters。有了这个,for-statement应该是这样的:

for(QuerySentence q : doclist)
{
    System.out.println("In loop : " + q.getLabel() + q.getQuery());
}

答案 1 :(得分:1)

doclist.add(qs1);
doclist.add(qs2);

答案 2 :(得分:0)

索引不需要像这样添加

doclist.add(qs1);
doclist.add(qs2);

答案 3 :(得分:0)

       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);
                }

        }