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
What is method overloading and method overriding?
Can each java object keep track of all the threads that want to exclusively access it?
Why should I use abstract class?
how to write a server program and sending the mails to the server using smtp protocol please help me
Differences between C and Java?
Can finally block be used without a catch?
Explain about core java?
Can we declare register variable as global?
Explain about the security aspect of java?
Explain tree set and its features?
What is the purpose of an interface?
What is a Hash Table? What are the advantages of using a hash table?
What is polymorphism in java? What are the kinds of polymorphism?
Explain about the select method with an example?
why Java does not support multiple inheritances?