Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

clone()

Example

Generate a duplicate of a list.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList<String> cars = new LinkedList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

LinkedList cars2 = (LinkedList)cars.clone();

cars2.set(0, "Toyota");

System.out.println(cars);

System.out.println(cars2);

}

}

Definition and Usage

The clone() method yields a copy of the LinkedList as an Object.

This produces a “shallow” copy, implying that object copies within the list are not generated; instead, the list contains references to the same objects as the original list.

Note: Since the return type is Object, it needs to be typecasted to use it as a LinkedList, as illustrated in the example above.

Syntax

public Object clone()

Technical Details

Returns: A duplicate of the LinkedList object.