You are on page 1of 1

ArrayList

Add Array: This program creates a new ArrayList called colors, adds some color
strings to it using the add() method,
and then prints out the collection using a for loop to iterate through each element
in the ArrayList.

Sort Array: This program creates an ArrayList called numbers, adds some integers to
it,
and then uses the sort() method from the Collections class to sort the ArrayList in
ascending order.
It then prints out the sorted ArrayList using a for loop to iterate through each
element in the ArrayList.

Copy Array:This program creates an ArrayList called numbers1, adds some integers to
it, and then
creates a second ArrayList called numbers2 and copies the contents of the first
ArrayList into it using the
ArrayList constructor that takes another collection as an argument. It then prints
out both ArrayLists to verify that the copy was successful.
this program creates a shallow copy of the ArrayList, which means that both
ArrayLists will reference the same objects in memory.
If you modify an element in one ArrayList, it will also be modified in the other
ArrayList. If you want to create a deep copy of the ArrayList,
where the objects themselves are copied instead of just the references, you will
need to implement your own copy method or use a library

Extract Array:we first create an ArrayList of strings named names and add some
elements to it.
We then extract a portion of the ArrayList using the subList() method, which takes
two arguments-
the starting index (inclusive) and the ending index (exclusive) of the portion to
be extracted.
The method returns a List object that contains the extracted portion of the
ArrayList. Finally,
we print the extracted portion of the ArrayList using the System.out.println()
method.

Swap Array: we first create an ArrayList of integers named numbers and add some
elements to it.
We then print the original ArrayList using the System.out.println() method.
Next, we swap two elements in the ArrayList using the Collections.swap() method,
which takes three arguments -
the ArrayList, the index of the first element to be swapped, and the index of the
second element to be swapped.
Finally, we print the modified ArrayList using the System.out.println() method.

You might also like