Question:
Writing my own clone() method in java?
Jason M
2011-09-27 12:16:51 UTC
For an assignment I have to write my own iterator class. I have made everything but the clone method as I have no idea how to do this. I have tried other forums but everyone says "Figure it out, you won't learn anything". Well, I have tried and tried and obviously have not learned anything by "Figuring it out" so please don't say "Just figure it out". It is due today and I am just looking for a simple solution.

Below is my clone() code so far:

public Object clone() {
LinkedList theClone = null;
try {
theClone = (LinkedList) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("Can't clone LinkedList.\n");
System.exit(1);
}

// Add code to do a "deep copy" (copy each Node in
// the current list.)
}

There is an internal Node class with the following code:
// The following inner class provides the node structure for a simple
// linked list.
private class Node {
private Node link; // Reference to next cell.
private E data; // Reference to data object.

// The following constructor creates a node with fields
// initiallized as specified by the two parameters.
Node(Node n, E o)
// PRE:
// n -- reference to Node which follows the new one.
// o -- reference to data for the new Node.
// POST:
// "link" and "data" are references matching the parameters.
{
link = n;
data = o;
}

// Accessor methods follow.

public Node getLink()
// POST: returns a reference to the cell following the
// current one.
{
return link;
}

public E getData()
// POST: returns a reference to the data object for
// the current cell.
{
return data;
}

// Mutator methods follow.
public void setLink(Node n)
// PRE: "n" is a new node.
// POST: "link" is set to the value of the parameter.
{
link = n;
}

public void setData(E o)
// PRE: "o" is the new data value for the current node.
// POST: "data" is set to the value of the parameter.
{
data = o;
}
}
}
Three answers:
kennywalter.com
2011-09-27 13:25:39 UTC
Start with this:

publicSomeClass implemets Cloneable

{

//some attributes

...

//some methods

public Object clone()

{

//create new someClass and deep copy elements from this to someClass

SomeClass someClass = new SomeClass();

someClass.attr1 = this.attr1;

...

return someClass;

}



}
anonymous
2016-11-13 05:52:49 UTC
Clone Method In Java
anonymous
2016-03-01 04:51:22 UTC
You don't declare the variable "result" in this snip so I assume it's a linked list of Particles. That, and the error message, means that you will want to cast your new Object[0] into a Particle before adding it to the list. Also, this looks wrong: result.addAfter(my_clone_method.i… new Object[0])); Shouldn't it be my_clone_method(new Object[0])? Edit: Aha, the ... is caused by Yahoo truncating words? Nevermind the last part then.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...