2012-08-28 17 views
0

当我注销sectionList时,有20个项目;出于某种原因,除了最后一项之外的所有内容都将输入到Array部分。有人可以看到这里有什么错吗?ArrayList数据没有正确传输到Java中的Array

更新:我发布了有问题的整个班级;它相对较短。它来自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()]); 


    } 
+1

为了更快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 –

+0

对我来说似乎很好。 –

+0

@KickingLettuce你可以使用'ArrayList.toArray'。另外,如果你想要订购密钥,可以使用'TreeMap'。 – oldrinb

回答

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 ...

集合的迭代器按升序返回键。

+0

我很抱歉,我在循环中有错误的代码。我已经更新了顶部并添加了更多。 – KickingLettuce

+0

@KickingLettuce为什么你循环两次复制数组? – oldrinb

+0

@KickingLettuce你在哪里登录以确定它是一个短? – oldrinb

1

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

+0

您必须移除'nextElement'定义以防止出现'ArrayIndexOutOfBoundsException'。 – oldrinb

+0

我已更新代码;你在最后一个for循环中看到的那个部分被错误地留下了。 – KickingLettuce

+0

@veer:正确更改了我的答案。 –