Powered by Blogger.

Copy Elements of Vector to Java ArrayList Example

>> Sunday, October 17, 2010

  1. /*
  2. Copy Elements of Vector to Java ArrayList Example
  3. This java example shows how to copy elements of Java Vector to Java ArrayList using
  4. copy method of Collections class.
  5. */
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.Vector;
  9. public class CopyElementsOfVectorToArrayListExample {
  10. public static void main(String[] args) {
  11. //create a Vector object
  12. Vector v = new Vector();
  13. //Add elements to Vector
  14. v.add("1");
  15. v.add("2");
  16. v.add("3");
  17. //create an ArrayList object
  18. ArrayList arrayList = new ArrayList();
  19. //Add elements to Arraylist
  20. arrayList.add("One");
  21. arrayList.add("Two");
  22. arrayList.add("Three");
  23. arrayList.add("Four");
  24. arrayList.add("Five");
  25. /*
  26. To copy elements of Java Vector to Java ArrayList use,
  27. static void copy(List dstList, List sourceList) method of Collections class.
  28. This method copies all elements of source list to destination list. After copy
  29. index of the elements in both source and destination lists would be identical.
  30. The destination list must be long enough to hold all copied elements. If it is
  31. longer than that, the rest of the destination list's elments would remain
  32. unaffected.
  33. */
  34. System.out.println("Before copy ArrayList Contains : " + arrayList);
  35. //copy all elements of Vector to ArrayList using copy method of Collections class
  36. Collections.copy(arrayList,v);
  37. /*
  38. Please note that, If ArrayList is not long enough to hold all elements of
  39. Vector, it throws IndexOutOfBoundsException.
  40. */
  41. System.out.println("After Copy ArrayList Contains : " + arrayList);
  42. }
  43. }
  44. /*
  45. Output would be
  46. Before copy ArrayList Contains : [One, Two, Three, Four, Five]
  47. After Copy ArrayList Contains : [1, 2, 3, Four, Five]
  48. */

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.