DuskFall
DuskFall

Reputation: 422

Strange behaviour with ArrayList

I'm in the process of building a basic database using csv files, and i'm currently testing the select function out when i ran into something strange.

private ArrayList<Record> selectField(String selectTerm)
{
    Log.log("Selection " + selectTerm,2,"DB_io");

    ArrayList<Record> ret = new ArrayList<Record>();

    if (titleRow.values.contains(selectTerm))
    {
        Log.log("Adding values to " + selectTerm);
        int ordinal = titleRow.values.indexOf(selectTerm);
        Log.log("Ordinal " + ordinal);
        List<String> tempList = new ArrayList<String>();

        for (Record r : data)
        {
            List<String> tempList = new ArrayList<String>();
            tempList.add(r.values.get(ordinal));
            Record s = new Record(tempList);
            ret.add(s);
            tempList.clear();
        }

        Log.log("Number of records in ret " + ret.size());
        for (Record t : ret)
        {
            Log.log(t.toString());
        }

    }
    else
    {
        Log.log("keyField does not contain that field");
        return null;
    }

    Log.log("Values " + ret.toString());
    return ret;
}

When i do this, the part where it logs t.ToString() shows the record to be empty, whereas if i log it before tempList.clear(), it shows the record to be containing data like it should.

If i move the tempList declaration into the Record r : data loop, then it works fine and the Record t : ret loop works outputs the contents of the record like it should

Why is this?

Edit : Record class

public class Record
{
    List<String> values = new ArrayList<String>();

    public Record(List<String> terms)
    { 
        this.values = terms;
    }

    public Record(String[] s)
    {
        this.values = Arrays.asList(s);
    }

    public String toString()
    {
        return values.toString();
    }
}

Upvotes: 1

Views: 97

Answers (2)

Bassem Reda Zohdy
Bassem Reda Zohdy

Reputation: 12942

you are referencing object from more than one place and clear method is cleaning object by setting its reference to null:

instead of ret.add(s); you can use ret.add(s.clone());

Upvotes: 0

Eran
Eran

Reputation: 393771

Your Record instance holds a reference to the ArrayList instance you passed to its constructor. Therefore, when you call tempList.clear(), you clear the same List that your Record instance is holding a reference to.

You shouldn't call tempList.clear(), since you are creating a new ArrayList in each iteration of your loop anyway.

Upvotes: 6

Related Questions