Saturday, July 25, 2009

How do you combine two arraylists in Java? (without loops)?

I'd rather not have to do two loops. Does Java have a built in method?

How do you combine two arraylists in Java? (without loops)?
Since ArrayList implements the Collection interface, you can do the following.





import java.util.ArrayList;


public class Merge{


   public static void main(String[] args){


      ArrayList pets = new ArrayList();


      pets.add("fish");


      pets.add("cat");





      ArrayList animals = new ArrayList();


      animals.add("birds");


      animals.addAll(pets);


   }


}
Reply:All class of Java collection API has the method


addAll( Collection%26lt;T%26gt; e)


which adds all element of a collection to another collection. It probably returns a boolen value which indicates whether correctly added or not.


It may through exception but I'm not sure. Follow the link from prev question for details.
Reply:http://java.sun.com/j2se/1.5.0/docs/api/...



small business web

No comments:

Post a Comment