Java ArrayList clone() method with example

Java ArrayList clone() method Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)

Method Signature

public Object clone()

Overrides: clone method in class Object


a clone of this ArrayList instance

See Also: Cloneable

ArrayList clone() method implementation

public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);

Java ArrayList clone() method example


import java.util.ArrayList;

public class CloneExample {

	public static void main(String[] args) {

		// Create empty arraylist
		ArrayList<StringBuilder> arrayList = new ArrayList<StringBuilder>();

		// adding StringBuilder object to arrayList
		arrayList.add(new StringBuilder("Welcome"));

		 * clone new arraylist arrayListClone from arrayList. Returns a shallow copy of
		 * ArrayList (arrayList). Shallow copies just copies the object reference. If
		 * changes done in real object affected in both list
		ArrayList<StringBuilder> arrayListClone = (ArrayList<StringBuilder>) arrayList.clone();

		StringBuilder sb = arrayListClone.get(0);
		sb.append(" to");

		System.out.println("Both list posting to same StringBuilder reference ");
		System.out.println("List 1 StringBuilder ");
		for (StringBuilder stringBuilder : arrayList) {
		System.out.println("List 2 StringBuilder ");
		for (StringBuilder stringBuilder : arrayListClone) {



Both list posting to same StringBuilder reference
List 1 StringBuilder
Welcome to
List 2 StringBuilder
Welcome to

Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. Java ArrayList remove(Object o) method with example
  2. Java ArrayList remove() method with example
  3. Java ArrayList ensureCapacity() method with example
  4. Java ArrayList indexOf() method with example
  5. Java ArrayList add(int index, E element) method with example
  6. Java ArrayList forEach() method with example
  7. Java ArrayList add(E e) method with example
  8. Java ArrayList addAll(int index, Collection c) method with example
  9. Java ArrayList addAll(Collection< ? extends E> c) method with example
  10. Java ArrayList clone() method with example
  11. Java ArrayList get() method with example
  12. Java ArrayList removeAll() method with example
  13. Java ArrayList contains() method with example
  14. Java ArrayList isEmpty() method with example
  15. Java ArrayList clear() method with example

Be the first to comment

Leave a Reply