gpt4 book ai didi

java - ArrayList 数据无法正确传输到 Java 中的数组

转载 作者:行者123 更新时间:2023-12-01 19:01:23 24 4
gpt4 key购买 nike

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

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


}

最佳答案

    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);
}

为什么要在这里复制数组两次?另外,为什么不使用迭代器呢?实际上,您真正应该使用的是 ArrayList.toArray转换为 String[],例如

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

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

The set's iterator returns the keys in ascending order.

关于java - ArrayList 数据无法正确传输到 Java 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12151719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com