ArrayList数据未正确传输到Java中的Array

时间:2012-08-28 01:38:53

标签: java android arrays arraylist

当我注销sectionList时,有20个项目;由于某种原因,除了最后一项之外的所有项目都被输入到数组中。有人可以看到这里有什么不对吗?

更新:我发布了整个课程;它相对较短。它来自Android应用程序。

public class ItemAdapter extends ArrayAdapter<ItemObject> implements
        SectionIndexer {

    private HashMap<String, Integer> alphaIndexer;
    private String[] sections;
    private LayoutInflater inflater;

    public ItemAdapter(Context context, ItemObject[] objects) {
        super(context, R.layout.item_row_layout, objects);

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        alphaIndexer = new HashMap<String, Integer>();
        int size = objects.length;

        for (int i = 0; i < size; i++) {

            ItemObject it = objects[i];
            String name = it.name;
            String s = name.substring(0, 1);
            s = s.toUpperCase();

            if (!alphaIndexer.containsKey(s)) {
                alphaIndexer.put(s, i);
            }
        }

        Set<String> sectionLetters = alphaIndexer.keySet();
        ArrayList<String> sectionList = new ArrayList<String>(sectionLetters);
        Collections.sort(sectionList);
        sections = new String[sectionList.size()];

        sections = sectionList.toArray(new String[sectionList.size()]);


    }

2 个答案:

答案 0 :(得分:3)

    for (int i = 0; i < sectionList.size(); i++) {
        sections[i] = sectionList.get(i);
    }

    for (int i = 0; i < sections.length - 1; i++) {
        sections[i] = sectionList.get(i);
    }

为什么要在这里复制数组两次?另外,为什么不使用Iterator?实际上,真正使用的内容是ArrayList.toArray转换为String[],例如

sections = sectionList.toArray(new String[sectionList.size()]);

此外,您可以使用TreeMap而不是HashMap对密钥进行排序,只需执行TreeMap.keySet ...

  

set的迭代器按升序返回键。

答案 1 :(得分:1)

我认为背后的原因是for循环i < sections.length - 1;中的条件。您可能只在for循环中记录sections[i]