Mysterious List behaviour

Hi,

I have a small function, and I don't understand it's behaviour. I hope some can explain me what happens:

publicstatic List findList(JdbcSupport jsi, List list, RMObjectJdbc cls,long Id, String sql, Connection c)throws Exception{

PreparedStatement ps = jsi.prepareStatement(sql,c);

ps.setLong(1, Id);

ResultSet srs = ps.executeQuery();

int p = 0;// a query is done and has three results

for (; srs.next(); ){

RMObject e = cls.getByIdSimple(srs.getLong(1), c);

list.add(e);//result is added to list

System.out.println("findList:"+e.getClass().getName()+":"+Id+","+0+","+e.get_id()+","+e.hashCode());

//check properties, "e" really exist

System.out.println("+"+list.get(p).hashCode());

//also the hashcode of "e" is printed corrctly

p++;

}

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

System.out.println(i+"-"+list.get(i).hashCode());

// but here, all the elements of the list are replaced by the last, how is that possible?

//that is my question

}

srs.close();

return list;

}

You can see the results of the screen-output

findList:nl.zorggemak.jdbc.orm.openehr.rm.datatypes.basic.DvIdentifierJdbcImpl:1,0,27,766399937

+766399937

findList:nl.zorggemak.jdbc.orm.openehr.rm.datatypes.basic.DvIdentifierJdbcImpl:1,0,28,766399954

+766399954

findList:nl.zorggemak.jdbc.orm.openehr.rm.datatypes.basic.DvIdentifierJdbcImpl:1,0,29,766399971

+766399971

0-766399971

1-766399971

2-766399971

So, why are all three elements of the list replaced by the last added?

It happens outside the loop.

If I don't ant this to happen, what a I do?

Thanks for any help

BertV>

[2598 byte] By [BertVa] at [2007-11-27 11:59:09]
# 1

cls.getByIdSimple(srs.getLong(1), c);

is returning the same object every time, rather than creating a new one, and just changing that object's state each time the method is called.

jverda at 2007-7-29 19:23:58 > top of Java-index,Java Essentials,Java Programming...
# 2

Thanks for your reply.

It looks like you are right, but as you can see on the output, I think that you are right, stupied, took me all evening to find out, and I did not see it, it is obvious.

Thanks, I will try immediately

BertVa at 2007-7-29 19:23:58 > top of Java-index,Java Essentials,Java Programming...
# 3

"Why does my list have the last element I added in all the positions" is a very common question here, so it's easy to spot and diagnose.

jverda at 2007-7-29 19:23:58 > top of Java-index,Java Essentials,Java Programming...
# 4

I understand the error I made. Thanks, but it needs some code rewrite, and it is one-o-clock in the night, I am tired. Thanks again, really very helpful.

Bert Verhees

BertVa at 2007-7-29 19:23:58 > top of Java-index,Java Essentials,Java Programming...
# 5

You're welcome.

jverda at 2007-7-29 19:23:58 > top of Java-index,Java Essentials,Java Programming...