Friday 22 April 2011

Example code --How to copy elements of Arraylist to vector

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

No comments:

Post a Comment