![](/img/trans.png)
[英]How to store ArrayList into sharedPreferences in 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.