Java Clone Method
Was wondering if there was any coders here. I'm trying to recreate my own clone method. This is what I have so far. I was wondering if anyone could help walk me through it?
public void copy(Intcoll4 obj) {
if (this != obj) {
c = null;
ListNode j = obj.c, k = null, t = new ListNode();
while (j != null) {
t.info = j.info;
if (k != null)
k.link = t;
else
c = t;
k = t;
t = new ListNode();
j = j.link;
}
how_many = obj.how_many;
October 18, 2014
6 Comments • Newest first
@tue61512: Oh I see. Well, if you need any further assistance, feel free to PM me
[quote=MarshMallows]This is horrible coding dude..simply use an insert function and loop through the linked list.
Here's something in pseudo-code / python:
I'm going to assume you have an insert function and the head refers to the first node on the list.
def clone (ListToClone):
ListClonePointer = ListToClone.head to the list to clone's first node
ClonedList = new LinkedList() the clone
for inter in xrange(ListToClone.length)
---ClonedList.insert(ListClonePointer.value()) current nodes value into new list
---ListClonePointer = ListClonePointer.next() to the next node over
return ClonedList[/quote]
I literally just started practicing code this month so I'm not too good at it as you can tell from my code.
This is horrible coding dude..simply use an insert function and loop through the linked list.
Here's something in pseudo-code / python:
I'm going to assume you have an insert function and the head refers to the first node on the list.
def clone (ListToClone):
ListClonePointer = ListToClone.head to the list to clone's first node
ClonedList = new LinkedList() the clone
for inter in xrange(ListToClone.length)
---ClonedList.insert(ListClonePointer.value()) current nodes value into new list
---ListClonePointer = ListClonePointer.next() to the next node over
return ClonedList
I never use the clone method, but isn't it supposed to return something. Like you have:
Class newObject = originalObject.clone();
Also if you're showing your code to others make sure your variables are properly named. No one knows what a "k" is.
In my main, I have a linked list object created. I'm trying to make a copy of it.
what exactly are you trying to do? make that copy of Intcoll4 into another class?