Append all elements of other Collection to Java ArrayList Example

  1. /*
  2.   Append all elements of other Collection to Java ArrayList Example
  3.   This Java Example shows how to append all elements of other Collection object
  4.   at the end of Java ArrayList object using addAll method. This program shows
  5.   how to append all elements of Java Vector to Java ArrayList object.
  6. */
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Vector;
  10.  
  11. public class AppendAllElementsOfOtherCollectionToArrayListExample {
  12.  
  13. public static void main(String[] args) {
  14.  
  15. //create an ArrayList object
  16. ArrayList arrayList = new ArrayList();
  17.  
  18. //Add elements to Arraylist
  19. arrayList.add("1");
  20. arrayList.add("2");
  21. arrayList.add("3");
  22.  
  23. //create a new Vector object
  24. Vector v = new Vector();
  25. v.add("4");
  26. v.add("5");
  27.  
  28. /*
  29.   To append all elements of another Collection to ArrayList use
  30.   boolean addAll(Collection c) method.
  31.   It returns true if the ArrayList was changed by the method call.
  32.   */
  33.  
  34. //append all elements of Vector to ArrayList
  35. arrayList.addAll(v);
  36.  
  37. //display elements of ArrayList
  38. System.out.println("After appending all elements of Vector,
  39. ArrayList contains..");
  40. for(int i=0; i<arrayList.size(); i++)
  41. System.out.println(arrayList.get(i));
  42.  
  43. }
  44. }
  45.  
  46. /*
  47. Output would be
  48. After appending all elements of Vector, ArrayList contains..
  49. 1
  50. 2
  51. 3
  52. 4
  53. 5
  54. */

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!