what is the use of clone() in real time scenario?
Answer Posted / aravinda reddy
Further to above a small update, clone will peform shallow
copy.Please execute below example and check the output.
public class CloneExamples {
public static void main(String[] args) {
ArrayList al = new ArrayList();
for(int i = 0; i < 10; i++ )
al.add(new Int(i));
System.out.println("al: " + al);
ArrayList al1 = (ArrayList)al.clone();
// Increment all al1's elements:
for(Iterator e = al1.iterator(); e.hasNext
(); )
((Int)e.next()).increment();
// See if it changed al's elements:
System.out.println("al: " + al);
System.out.println("al1: " + al1);
}
}
class Int {
private int i;
public Int(int ii) { i = ii; }
public void increment() { i++; }
public String toString() {
return Integer.toString(i);
}
}
o/p:
al: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
al: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
al1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
the old ArrayList and the cloned ArrayList are aliased to
the same objects
| Is This Answer Correct ? | 6 Yes | 8 No |
Post New Answer View All Answers
How can we use primitive data types as objects?
How many types of array are there?
What is the difference between throw and throws keywords?
why are wait(), notify() and notifyall() methods defined in the object class? : Java thread
What is the output of the below java program?
Explain java heap space and garbage collection?
What is java util hashmap?
Can a constructor call the constructor of parent class?
Explain about field hiding in java?
What are the 4 versions of java?
Is arraylist ordered?
What are the different ways of creating thread?
What is meant by flickering?
What is console based application in java?
What is the difference between procedural and object-oriented programs?