繁体   English   中英

如何声明arraylist在android中存储整数和字符串?

[英]How to declare arraylist to store integers and strings in android?

我是arraylist概念的新手。 请帮助我如何声明arraylist并添加字符串和整数。

String str = quesid+","+k1;
                             ArrayList<Object> arl=new ArrayList<Object>();
                             arl.add("str");

在上面的代码中,字符串没有添加到arraylist。 哪里出错了...请帮助我

提前致谢...

创建一个custom class ,并将String和Int成员字段现在也为该类中的那些字段创建一个getter()setter()方法,现在在ArrayList中使用该类,简单:-)

编辑:示例

List<CustomClass> foo = ArrayList<CustomClass>


public class CustomClass
{
  private String result;
  private int count;

  public CustomClass() {
    super();
    // TODO Auto-generated constructor stub
   }
   public void setResult(String res)
   {
     this.result=res;
   }
   public void setCount(int cnt)
   {
    this.count=cnt;
   }

   public String getResult()
   {
    return this.result;
   }
   public int getCount()
   {
    return this.count;
   }

}

在你的活动中,

 List<CustomClass> foo = ArrayList<CustomClass>
      CustomClass cust = new CustomClass();
      cust.setResult("Test");
      cust.setCount(1);

      foo.add(cust);

要检索数据......

 String res = foo.get(0).getResult();
 int count = foo.get(0).getCount();

您可以通过将值传递给CustomClass构造函数来直接设置值 。(在这种情况下,您必须修改CustomClass的构造函数)选择是您的。

如此定义一个类:

public class StringInt{

private String s;
private int i;

public StringInt(String o1, int o2){
s = o1;
i = o2;
}

public String getString(){
return s;
}

public int getInt(){
return i;
}

public void setString(String s){
this.s = s;
}

public void setInt(int i){
this.i = i;
}

}

然后使用在ArrayList中

ArrayList<StringInt> arl = new ArrayList<StringInt>();
arl.add(new StringInt("Test", 15));

编辑:user370305有相同的想法。 英雄所见略同? :P

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM