2011-12-03 52 views
1

我是新的陣列概念。請幫助我如何聲明數組列表並向其中添加字符串和整數。如何聲明arraylist在android中存儲整數和字符串?

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

在上面的代碼中,字符串沒有添加到arraylist。我在哪裏出了錯?plz幫助我提前

謝謝...

+0

你真的想要將String和Integer存儲在同一個數組中嗎?因爲這不是一個好的Java練習... – havexz

回答

5

做一個custom class,並把字符串和Int成員字段現在也做的吸氣劑()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的構造函數)選擇是你的設置值。

+0

嗨,謝謝你的迴應....你能舉個例子嗎? – RaagaSudha

+0

很好的答案,謝謝 – Ahmad

+1

爲什麼這個不被接受?這是最好的答案 –

2

定義一個類,如:

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

相關問題