0

I have a list which has object(record) taken from database. I need to add it another list of generic class inside a loop.When ever loop executes the final list contains only the last element.my coding are..

List<modelclass> mdlclasslist=new ArrayList();
for(Class_1 a:class1list) {
  Query qr=s.createQuery("from Class_2 where ID= :f and code= :j order by mark desc");
  qr.setParameter("f",id);
  qr.setParameter("j",code);
  List<Class_2> b=new ArrayList();
  b=qr.list();
  for(Class_2 cls:b) {
    modelclass mdl=new modelclass(cls.getID(),cls.getCode(),cls.getMark());
    mdlclasslist.add(mdl);
  }
}

mdlclasslist contains same object.It is not adding every object the query takes.please advice.

3
  • 1
    are you sure you are getting more than one record in b=qr.list(); Commented Dec 27, 2013 at 9:47
  • Where are you using "a" object of class Class_1 in for(Class_1 a:class1list)...? Commented Dec 27, 2013 at 9:53
  • Got it.I have to use a.id and a.code to get a new record..Thank for all your help Commented Dec 27, 2013 at 10:42

5 Answers 5

1

Your Query appears to return the same list over and over again for every Class_1 item because id and code never change. I assuming your code should rather look like this:

Query qr=s.createQuery("from Class_2 where ID= :f and code= :j order by mark desc");

for( Class_1 a : class1list ) 
{
    qr.setParameter( "f", a.id );
    qr.setParameter( "j", a.code );

    for( Class_2 cls: qr.list() )
    {
        modelclass mdl=new modelclass(cls.getID(),cls.getCode(),cls.getMark());
        mdlclasslist.add(mdl);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

How about debugging and printing out the number of elements in the 2nd list before adding? Not sure if you want to append the List you retrieve from a DB to the one you initialize beforehand... However, I would define the 1st List to be of the generic type Class_1 (BTW: read about Java naming conventions) and then use addAll

yourList.addAll(theListFromDB);

Comments

0

try this

listInstance.addAll(anotherListInstavce) ;

Comments

0

First i would check if my source list, the one populated from DB has more than 1 element. If you are using JDBC, its a very common mistake to not move the result set objects further.

Secondly if you need such collection manipulation utilities i suggest take a look at commons-collections ListUtils class.

Comments

0

All the collections have a simple method to add data of one collection to other.

list2.addAll(list1);

You can simply use this method...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.