Redundant serialization of linked list and pointer into list - java

I have kind of a contrived question.
Let's say I have a linked list of users, and one of these users is "User of the week":
public class UserOfTheWeek implements Serializable {
private UserNode root;
private UserNode userOfTheWeek;
//...
private class UserNode {
String username;
UserNode next;
}
public void saveToFile() {
ObjectOutputStream oos = new ...
oos.writeObject(root);
oos.writeObject(userOfTheWeek);
}
}
root obviously stores a reference to the head of the list, and userOfTheWeek could point to any of the nodes. I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list? If the user at the head of the list happens to be the user of the week, this could save the entire list twice, and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
Does anyone know what will happen? And if not, I am also open to an alternate solution.

I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list?
No.
If the user at the head of the list happens to be the user of the week, this could save the entire list twice
No.
The stream knows which objects have already been serialized to it, and doesn't reserialize them. See the Object Serialization Specification #1.2. Similarly, the object is only deserialized once. Object graphs can be serialized and recovered in full generality, including cycles.
and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
You would have to serialize and deserialize that separately, but it won't result in creation of a new object, it will refer to an object in the list.

Related

Cloning a LinkList without using any builtin functions.

I went to interview today and this question got thrown at me. I can't come up with an answer.
the gig is
SList2 = SList1.clone();
if you change things in SList1 (e.g editing the object) it will not affect the similar object in SList2. I attempt it, I create new nodes but whenever I get to the cloning object part I failed. Was thinking about object.clone() but the question state that no built-in function is allowed.
Slist2.head = new Node();
Node newList = Slist2.head;
Node head = Slist1.head;
Slist.head.(all data) = head.(all data);
while(head.hasNext()){
head = head.next();
Node newGuy = newNode();
newNode.(all data) = node.(all data)
newList.next = newGuy;
}
This will follow through the old list, manually copying all data into a new node and tacking that node on to the new list
This is two problems disguised as one.
How would I read in the values from the linked list object, and
How would I create it in such a way that no references were reused (that is, I don't just reassign the head of one list to the head of the other)?
Without diving into code, let's look at this at a high level. Provided that your linked list can provide iteration (that is, it has an Iterator-like object that keeps its state in the list, and returns a node when next() is referenced), then the first problem becomes a matter of iterating over the linked list via the iterator.
From there, you would want to peel out the raw value from what you're iterating over, and add them into your new linked list object.
You're pretty much done then; nothing fancy needs to be worked out. It's literally taking data from one structure and inserting it into another.

how to delete objects?

I have two classes:
Class Node {
int address
}
Class Link{
int latency;
int bandwidth;
Node node1;
Node node2;
}
public Link [] link= new Link[Nmax];
if I want to create a link between two nodes, it is easy, I've just to:
node1=new Node(); //and then I add parameter like address and so on
node2= new Node();//...............
link[1]= new Link();
link[1].node1=node1;
link[1].node2=node2;
link[1].latency=15; //and so on, we suppose that we have 100 nodes and 60 links
Now, during the program, sometimes we add some new nodes then we have to add links between them, I can do this with the same manner us above, my question is:
what I have to do if I want to delete a node ? (links between this node and other existing nodes must be deleted too)
--- Edited in response to jpm's excellent observation ---
In your case, you are doing all of the data structure management yourself, but are not storing enough infomation to undo the additions to the data structure.
You need to store enough information at create time to support the other operations on the data structure. This means that perhaps the choice of an array as your high-level exposed data structure is a bad choice, because there is no guarantee that additions will maintain the sufficient information to support the removals.
Wrap the array in an object, and write the code in the add(...) method to support the efficient removal. This probably means storing more information, which was constructed specifically for the support of removal.
--- Original post follows ---
To delete an object in Java, ensure that nothing "points" to it (has a reference to it) and then wait. Automatic garbage collection will do the deleting for you.
An example to make this clear
link[1] = new Link();
// now we have an extra Link in our array
link[1] = null;
// now garbage collection will delete the recently added Link object.
Note that if you have two or three references to the created Link object, it will not be collected until all the references are lost
link[1] = new Link();
// now we have an extra Link in our array
Link current = link[1];
// now we have two references to the newly created Link
link[1] = null;
// now we have one reference to the newly created Link
current = null;
// now the newly created Link is a candidate for garbage collection
The way this is implemented is there is a top-level Thread of the user implemented program. If that thread can reach the Object in question then it won't get garbage collected. This means that rings and meshes of Objects that are no longer reachable from the live Threads will be collected in mass.
before deleting a node; loop over your links and remove any that have your node to be deleted as node1 or node2, then delete your node.
You probably want to explore using a better data structure than an array for this use case. You want to be able to inspect all Links, figure out which ones refer to the deleted Node, and remove those Links. Start looking at List/Set and see if they suit your needs, and slowly evolve into a good implementation that gives you what you need.
"Deleting" an object in Java means to remove all references that point to the object. The Garbage Collector then eventually will free the memory occupied by the object. So what you need to do, would be to set all references to a specific Node object to null.
// lets delete node1
link[1].node1 = null;
node1 = null;
// at some point the object will be deleted

How to retain the content of the variable on every call in java

Hi am developing a linked list in java.
In my system there will one master node where the master node will distribute the incoming request to one of its slave node.
In order to make use of cache memory, i initialized a linked list for each node (where all the content will be maintained in the master node).
I update the linked list of respective node before the node process any query (so that i can find what are request recently processed by the respective nodes).
But the problem is, at an instance when i try to find the content of the linked list its empty. Even when i try to add new content, it creates the list newly and then add the content. I think the list is created newly every time when i access the java file containing the linkedlist implementation.
Is it possible to retain the content of the linked list and update the linked list with the previous content. Is their any inbuilt function in java to retain the state of the variable or where can i initialize the list in order to achieve what i expect.
My code is as follow
import LinkedList.QueueImplement;
public class Node {
protected LinkedList<String> list;
public Node(String address, String serviceName) {
this.list=new LinkedList<String>();
}
public void addlist(String data) {
list.add(data);
}
}
I suspect the problem is just that every Node constructs its own LinkedList, as is clearly shown in the little code we see. If the variable list were marked static, and constructed at its declaration rather than in the constructor, then all Nodes would share a single LinkedList, which is probably what you want.

Storing objects in link lists

I've been asked to create and manage a link list from scratch without the use of the java util.
If I were to create an object which has more then one attribute e.g. name & age then would it be possible to store the object within the link list?
I'm having a hard time trying to get my head around this and would appreciate any help!
Here's my pseudo code:
Classes:
Node
LList
Person
Address
add_person
sout "Enter name"
scan.next(String name)
pass name to setName (a Person class function)
sout "Enter postcode"
scan.next(String postCode)
pass postCode to setPostCode (a Address class function)
How would I then go about linking these two bits of information together within the same link list?
Edit: Thanks for the input guys, I'll have a good read about based upon your recommendations! Once again many thanks! :)
Try looking up what a linked list is and how it needs to be constructed. Your psuedo code has nothing to do with a linked list, only some rudimentary data entry. I suggest you look over the following link to understand what it is and how it works. The actual coding is fairly simple once you understand the structure.
I encourage others to not do your homework for you.
Wikipedia
Its not too tough, you just need to create your own Node class. This class might look something like this:
public class Node{
protected String name;
protected int age;
//any additional data you need...
protected Node next;
//methods...
This class would contain many data fields and would provide methods to interact with these fields. The key component is the "protected Node next;" line, which is the next node in the linked list. All nodes in the list would have a next node, except for the tail. The tail node would set next equal to null.
First you need to define a basic building bloc of a linked list which is Node. Nodes are like containers that store whatever you want. That's why storedData variable is of type Object. You would define it like this:
public class MyNode{
Object storedData; // this is a reference to the object that you want stored in the list
MyNode next; //this is a reference to the next node in your list
...
}
Then you can define your linked list class, which would go like this:
public class MyLinkedList{
MyNode head; //this is a reference to the top element of your list
int nodeCount //
//put all the requkired methods here
}
You should write your own LinkedList that uses generics; let it handle any object type.
You name and post code and age and whatnot ought to be encapsulated in an object that you'd be able to add to the LinkedList.
package linkedlist;
public class Node<T> {
private Node<T> prev;
private Node<T> next;
private T value;
}

Question about linked lists in Java

Cat------>Dog------>Horse----->Parrot
^P1       ^P2       ^P3        ^P4
Draw the resulting linked list after executing the following statements:
P4 = P2;
P3.info = P2.info
etc.
My question is, what does '.info' reference?
I've looked in the API for both node and linked list and haven't found anything.
Any ideas?
This would entirely depend on the specific implementation used in your assignment, but it sounds like info contains the data of the specific node in the linked list, i.e. P1.info is Cat.
Each node in a standard linked list has two pieces of information:
A reference the the next node
The data contained in the current node
I'm not sure if your instructor wants you to take into account that you would have to "clone" the node in order to have a separate object with the same data or if your instructor wants you to take it literally where setting one object equal to another object simply makes the first one a reference to the second one.
As spookyjon said, the info appears to be a public variable in the node class for the data (cat, dog, horse, parrot).

Categories