TheLettuceMaster
TheLettuceMaster

Reputation: 15734

ArrayList Data not properly transferring to Array in Java

When I log out the sectionList there are 20 items; for some reason, all but the last item is being entered into the section Array. Can someone see whats wrong here?

UPDATE: I posted the entire class in question; it's relatively short. It is from an Android app.

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()]);


    }

Upvotes: 0

Views: 138

Answers (2)

obataku
obataku

Reputation: 29646

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

Why are you copying the array twice here? Also, why not use an Iterator? Actually, what you should really use is ArrayList.toArray to convert to String[], e.g.

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

Additionally, you can have your keys sorted by using a TreeMap as opposed to a HashMap, merely by doing TreeMap.keySet...

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

Upvotes: 3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

I think the reason behind that is the condition in the for loop i < sections.length - 1;. You are probably logging sections[i] only in the for loop.

Upvotes: 1

Related Questions