java arraylist add(int index,E element)方法问题

重新编辑下问题说明:

我想通过simpleadapter输出arraylist的值,由于我是指定位置的,当这个ArrayList某个位置有值时,第一个位置就会出现与其相同的结果。具体情况如下(我只对索引为2的赋了值,结果第一个位置也出现相同的):

Screenshot_2013-04-12-16-10-35.png

ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

for (int j = 0; j < 3; j++)

list.add(null);

HashMap<String, Object> map = new HashMap<String, Object>();

map.put("name", "jim");

map.put("year", 2009);

list.add(2, map);

ListView listview = (ListView)findViewById(R.id.listview);

listview.setAdapter(new SimpleAdapter(MainActivity.this, list, R.layout.item, new String[]{"name","year"}, new int[]{R.id.name,R.id.year}) {

});

回答:

第一,ArrayList不是Array,容量自动增加,不需要初始化。好吧事实上,Array也不需要初始化,因为新生成的Array所有值都是null或者primitive type的默认值,除非你用initializer

第二,add不是赋值,如果不确定,RTFM

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

而赋值是这个,同理请记得RTFM。

第三,如果你需要的是保证初始的容量足够大,用 带参数的构造函数

以上是 java arraylist add(int index,E element)方法问题 的全部内容, 来源链接: utcz.com/p/168906.html

回到顶部