Jump to content

Java automatic variable/object naming


Recommended Posts

I want to create a series of objects to be assigned to nodes in a linked list.

 

I need each object to have a unique name. Is there a way to create an object and have it named automatically.

 

The first object sr1 the second sr2 the third sr3 etc.

 

I've been messing about with various loops all after noon trying to concatenate strings and incrementing integer all afternoon but no joy assigning those combos as variable names.

 

Ideas please.

Link to comment
Share on other sites

As far as I know, no. You can not dynamically name objects in Java (however, I may be wrong). Why do they need names though? Especially if they are to be placed in a linked list?

 

One way to get around this is to add a name attribute to your objects along with appropriate get/set methods. Then, when you create the object, you can dynamically give it a name, and if you need to know who it is, you can just ask it.

 

Plus, when you create an object, technically, the name that you give it is simply the name given to the reference pointer that points to that object's location in memory. You are not, technically, naming the object. Once you place the object in the linked list, you will remove and lose the original reference to the object and, hence, according to your model, also lose the name. Therefore, if the objects do need "names", the above approach is better.

Link to comment
Share on other sites

Yes it looks like you are right I've searched and searched and can't find any way to create an object and name it automatically at the same time.

 

Although I could put it in an array and refer to in by it's subscript

array[];

 

I'm not familiar with linked lists just trying it out - so I'm not sure what you mean.

 

I thought that a linked list was just a series of pointers to objects contained and next and previous nodes.

 

Some experimentation coming up!

Link to comment
Share on other sites

I'm not familiar with linked lists just trying it out - so I'm not sure what you mean. 

 

I thought that a linked list was just a series of pointers to objects contained and next and previous nodes.

 

In a sense it is. However, another way of looking at them is that you have a series of containers and into each container you place an object. Once the object is in the linked list, the only way to get to it is by traversing the list. You lose the original reference to that object.

 

myObject = new Object();



linkedList.addObject(myObject);



myObject = null;

 

The above code may look like I have created an object and then destroyed it, but this is not what has happened. I have actually created an object with a reference to it -- myObject (the name of the reference and not the object) -- and then placed my object into my linked list. Now, there is a container/node in the linked list that points to my object (i.e. it is still in memory and can still be accessed), and then I simply kill the original reference.

 

Linked Lists are great, but they can be a little hard to conceptualize and understand in the beginning.

 

Good Luck

Link to comment
Share on other sites

Thanks again.

 

Now I get you!

 

I still haven't got it sussed but I have made progress.

 

 

This is a lab excercise which isn't due for a couple of weeks but I missed the lecture at which some of the stuff was covered. It's not being assessed but we'll move on to something else. However the same topics will almost certainly turn up as part of an assignment.

 

1.Read students records from a file (about 15 records), each record contains (Student-Name, Student-ID, Student-Age, Student-Address);

 

I've finished 1.

 

2. Store these records as (objects) in a linkedlist structure.

 

I've got as far as creating the StudentRecord object and storing substrings from each line as properties of the object.

 

 

Building the linked list is driving me up the walls!

 

I'm reading the file with

 

while(!File.EOF)

 

Each StudentRecord is being created in this loop as well

This is even working!

Though naturally the data in each object is lost again with each iteration. ( I just printed it to the screen to see it operate.)

 

But as yet failed to create a new node with each iteration. Back to the notes.

 

I'm going to give up for today. I'll pester my lecturer tomorrow.

Link to comment
Share on other sites

I can now create the linked list by coding it in one node at a time - not very dynamic.

 

Node n2 = new Node(objectr, n1);

 

My lecturer disapeared almost immediately after todays lecture so I didn't get the chance to ask.

 

But how do I go about creating a new list node inside a loop? I seem to be missing some basic information!

 

 

//reads studebt details from text file 

public class readRecords

{ 

 static StudentRecord r = new StudentRecord();



//creates new linked list and head node

 LinkedList list = new LinkedList();

 



 public static void main(String [] args)

 {//create and open file object

    uuTextFile F = new uuTextFile("sRecords.txt");

     F.OpenInputFile();

    

     while (!F.EOF)

     {

       

      String line = F.ReadLine();

     //pass string to constructor

      r = new StudentRecord(line); 

      

     }

   

   F.CloseInputFile();

  }

}//ends readRecords

 

After 3 days I've gotten no further. Some clues would be appreciated!

Link to comment
Share on other sites

Okay, one question -- are you building your own LinkedList class?

 

Basically, you create a LinkedList object, that object will have several methods. It is up to the LinkedList object/class to create the nodes.

 

As far as the main is concerned, all you need to do to add something to a linked list is to go

 

list.add(Object);

 

The Object is whatever you are placing into the linked list. Therefore, you need to do one of two things:

1. either place all the info -- the record -- into an object

2. or create a specialized linkedlist that holds the record

 

The first option is the best

 

Then, within the add method inside the Linked List you create the new node. This allows you to change the implementation of the Linked List code without it affecting the rest of your code.

 

Generally, inside of your linked list you will have an inner class that is called Node. it is this class that you use to create the new node.

 

(not real code) You add method would look something like this

 

public void add(Object o) {

   Node next = new Node();

   next.data = o;

   next.nextLink = head;

   head.next = next;

}

 

That is the general idea (although I think that is a mixture of Java and C)

 

Does that help, or just confuse the issue more?

Link to comment
Share on other sites

Let's discuss this conceptually and see what you really understand..

 

A pointer is a memory address that contains another memory address. The memory address is to you, a memory variable. The stuff below is not java, just concepts.

 

int myNum = 3;

pointer myPointer;

myPointer = addressOf(myNum)

 

To draw this out, you have

 

Variable Name | MyNum | myPointer

Address | 0x00000004 | 0x00000006

Value | 3 | 0x00000004

 

That's what it would like in a memory dump. The address values I just made up. You can see how myPointer contains a value equal to the address of MyNum

 

Now I can say

 

print(myPointer) gives me 0x000000004

print(myPointer->value) gives me 3

 

So now i can define a new pointer

 

pointer pointer2;

pointer2 = addressOf(myNum)

 

 

Now I have 2 pointers, myPointer and pointer2. Each has a separate memory address in the machine, but both contain the same value, the address of myNum and each can be used to obtain the value of 3.

 

Now lets say I do this again

 

Object myNode{

int number

}

 

myNode.number = 3

mypointer = myNode

print(myPointer.number)

 

In all these cases, we are defining the object being pointed to as a second variable. This is unecessary.

 

mypointer = new(myNode)

print(myPointer.number)

 

In this case, my pointer is created and so is a new object instanciated. The pointer points to the object. The object doesnt' have a name but i can still reference it through mypointer. If i destroy mypointer, in Java, the object should be destroyed if there are no other pointers pointing to it. This is called garbage collection. In C, you would be screwed because their is no garbage collection. The memory for the object would continue to exist but nothing would be able to reference it.

 

So now we get more complicated..

 

Object myNode{

int number

pointer nextPtr

}

 

myPointer = new(myNode)

myPointer.number = 3

myPointer.nextPtr = NULL

 

NextPtr points to nothing.

 

myPointer.nextPtr = new(myNode)

myPointer.nextPtr.number = 4

 

Now I've done it! I've created a new object in memory and pointed nextPtr to it. I now have a linked list.

 

myPointer -> myNode

                  myNode.nextPtr -> myNode

                                              myNode.nextPtr -> NULL

 

How about traveling the list?

currentPtr = mypointer

 

do while currentPtr.nextPtr is not NULL

currentPtr = currentPtr.nextPtr

enddo

 

Now currentPtr will travel through the list in a loop until the last object is reached. it will stop because the last pointer has a NULL value (nothing). You will note that during this process, I never destroyed my top pointer (myPointer). if I did, I would have no way of finding the first element in the list. I can continue this further by adding a prevPtr property and having it point to the previous node.

 

Does all that make sense? The best way to learn this is to draw objects on paper. Write the pointer name and draw an arrow to a circle which is the object. You can draw a chart. Go through the code and update the chart as you go along. You will get a good understanding of this as your brain gets the idea..

:wink:

Link to comment
Share on other sites

doesn't java have variable variables?

 

in php you can:

<?

$cat = 'dog';

$$cat = 'woof';

echo $dog; // will echo woof





class test_class

{

function test_class()

{

echo "Blahn";

}



function hello()

{

return "Moooooo!n";

}

}



$i = 1;

while($i < 5)

{

$j = "cow".$i;



echo $j." variable created belown";

$$j = new test_class();

echo $$j->hello();



$i++;

}

?>

 

[john@administrator Desktop]$ php variable.php

X-Powered-By: PHP/4.2.3

Content-type: text/html; charset=iso-8859-15

 

woof

cow1 variable created below

Blah

Moooooo!

cow2 variable created below  

Blah

Moooooo!

cow3 variable created below

Blah

Moooooo!

cow4 variable created below

Blah

Moooooo!

[john@administrator Desktop]$

Link to comment
Share on other sites

HashMap is what you want. It's a collection of Objects with a Key. You can assign the Key (it's another Object - can be a String) and reference the Object by it's key. So If I put an Object in a hashmap with a Key of "firstObject" then I can retrieve that Object from the HashMap using the name "firstObject"

 

Lok in the API docs for more details - but it essentially does what you are describing

Link to comment
Share on other sites

Hi and thanks for replies so far. I am making progress. Faster progress would be good!

 

Building my own linked list class. (I know theres already a linked list class)

 

Student records are objects to be stored in list nodes.

 

Theres quite a bit to take in in these posts so give me a day or too to work through this information.

 

I think of a node as an instance of class Node. Usually each instance has it's own identifier, I reckoned I needed a way to identify each node thats why I'm confused. Just needs more work to get my head wrapped round it. Haven't covered hash tables so far. I'll look into them.

Link to comment
Share on other sites

You know, if you do a search, you will probably find all the code you need on the web for a linked list. It tends to be a fairly standard learning exercise.

I have searched, continually it seems, but perhaps my lack of familiarity means I didn't recognise what was found as what I wanted!

Link to comment
Share on other sites

You know, if you do a search, you will probably find all the code you need on the web for a linked list. It tends to be a fairly standard learning exercise.

I have searched, continually it seems, but perhaps my lack of familiarity means I didn't recognise what was found as what I wanted!

Give this a shot. It is an article over at DevX that both explains a Linked List and has the code attached.

 

http://www.inquiry.com/techtips/cpp_pro/10...n/10min0599.asp

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...