[英]How to declare arraylist to store integers and strings in android?
I am new to arraylist concept. 我是arraylist概念的新手。 Please help me how to declare arraylist and add strings and integers to it.
请帮助我如何声明arraylist并添加字符串和整数。
String str = quesid+","+k1;
ArrayList<Object> arl=new ArrayList<Object>();
arl.add("str");
In the above code the string didnt added to arraylist. 在上面的代码中,字符串没有添加到arraylist。 Where I went wrong...plz help me
哪里出错了...请帮助我
Thanks in advance... 提前致谢...
Make a custom class
, and put String and Int member fields now also make a getter() setter() methods for that fields in that class, Now use that class in your ArrayList, Simple :-) 创建一个
custom class
,并将String和Int成员字段现在也为该类中的那些字段创建一个getter()setter()方法,现在在ArrayList中使用该类,简单:-)
EDIT: Example 编辑:示例
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;
}
}
In your activity, 在你的活动中,
List<CustomClass> foo = ArrayList<CustomClass>
CustomClass cust = new CustomClass();
cust.setResult("Test");
cust.setCount(1);
foo.add(cust);
To retrieve data... 要检索数据......
String res = foo.get(0).getResult();
int count = foo.get(0).getCount();
You can directly set a values by passing it to CustomClass constructor .. (In this case you have to modify constructor of CustomClass) Choice is yours. 您可以通过将值传递给CustomClass构造函数来直接设置值 。(在这种情况下,您必须修改CustomClass的构造函数)选择是您的。
Define a class as such: 如此定义一个类:
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;
}
}
Then use is in an ArrayList 然后使用在ArrayList中
ArrayList<StringInt> arl = new ArrayList<StringInt>();
arl.add(new StringInt("Test", 15));
Edit: user370305 had the same idea. 编辑:user370305有相同的想法。 Great minds think alike?
英雄所见略同? :P
:P
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.