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


Please Help Members By Posting Answers For Below Questions

What is method overloading and method overriding?

538


Can each java object keep track of all the threads that want to exclusively access it?

544


Why should I use abstract class?

575


how to write a server program and sending the mails to the server using smtp protocol please help me

1555


Differences between C and Java?

623






Can finally block be used without a catch?

548


Explain about core java?

631


Can we declare register variable as global?

517


Explain about the security aspect of java?

581


Explain tree set and its features?

602


What is the purpose of an interface?

562


What is a Hash Table? What are the advantages of using a hash table?

612


What is polymorphism in java? What are the kinds of polymorphism?

584


Explain about the select method with an example?

593


why Java does not support multiple inheritances?

707