先贴代码English.java
- Java code
package com.test;public class English{ public int id; public String word; public String definition; public String association; public int getId() { return id; } public String getWord() { return word; } public String getDefinition(){ return definition; } public String getAssociation(){ return association; } public void setId(int id) { this.id =id; } public void setWord(String word) { this.word= word; } public void setDefinition(String definition) { this.definition= definition; } public void setAssociation(String association) { this.association= association; } @Override public String toString() { return "id:"+id+"; word:"+word+"; 释义:"+definition+"; 联想:"+association; } }
主代码:
- Java code
package com.test;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.Window;import android.view.WindowManager;public class Test extends Activity { private English english; private List<English> englishes; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //去标题 getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN); //全屏模式 setContentView(R.layout.main0); englishes=new ArrayList<English>(); english=new English(); int j=0; String[] str={"a","b","c","d"}; for(int i=0;i<4;i++) { english.setId(i); english.setAssociation(str[i]); englishes.add(english); } while(j<englishes.size()) { Log.i("XML", Integer.toString(englishes.get(j).getId())); Log.i("XML", englishes.get(j).getAssociation()); j++; } } }
有点不明白englishes.size()有四个对象,为什么每次输出的结果都是3 d,谁能解释下,对于ArrayList<E>如何添加对象都迷惑了,谢谢!
------解决方案--------------------
Arraylist存放的是引用,你的4个元素中的引用都指向了同一个对象
这个对象
for(int i=0;i<4;i++)
{
english.setId(i);
english.setAssociation(str[i]);
englishes.add(english);
}
被你修改了4次,从a,b,c,d依次修改了一下,所以最后是d
------解决方案--------------------
1、ArrayList<E> list=new ArrayList<E>();中的E是指泛型,即,E 可以代表任何一种类型,这种类型就是要指定 list数组中存储的元素的类型,不指定是不能初始化的。比如,
- Java code
ArrayList<String> list=new ArrayList<String>(String);
------解决方案--------------------
我建议你还是去看看文档的,在哪你能得到你的答案