Easy dynamic object names in java?

Soldato
Joined
4 Nov 2003
Posts
5,738
Location
Edinburgh
I've got a loop running creating objects, but i don't know how to give the objects dynamic names such as "intCell(i)" in this case where i would be the loop counter. Surely there is any easy way, but my googling is weak and i'm not entirley sure what i should be looking for.

Code:
public static IntList array2intList(int[] i) {
       for (int j=0; j<i.length; j++) {
		IntCell intCell(i) = new IntCell(null, i[j], null);
	}
       return null;
    }
 
Are you saying you want to creat a load of objects at runtime and assign each of them to a unique named identifier?
 
You can't assign dynamic names to variables in Java. Java is a statically typed language which means that all variables must be explicitly declared. You need to use some sort of collection instead (Array, List, Map etc.) to hold you elements.
 
Just turn intCell into an array as in intCell. When you call it just call intCell[n]. n being the object index number.

And if I may hijack slightly can anyone tell me if it's possible to create dynamically sized arrays ala VB.NET. So far I can't find a way, I always need to declare a specific size for an array. I suppose I could go through a long winded copying one array to a holder array, redeclaring original array a new size and copying the array back from holder with room for the new variables but that would take an age and a half.
 
Right i had it as an IntCell array, becuase that was the only way i could think of doing it, and i got told by my tutor thats "over complicating thins"? I'm making a doubly linked list of objects, so they don't need to be held in an array technically. But i don't know how else i'd do this, i wish i'd just asked him now (i just thought at the time it would be fairly simple...) :(

List and/or map maybe what i want; i will have a play :)
 
LeperousDust, do you have the class definitions for IntList and IntCell, that would make it easier to help you.

I suppose I could go through a long winded copying one array to a holder array, redeclaring original array a new size and copying the array back from holder with room for the new variables.

You have esentially described an ArrayList. An ArrayList is a dynamic resizing collection backed by an array, this tutorial might help:

http://dotnetjunkies.com/WebLog/feelexit/archive/2004/06/15/16554.aspx
 
Last edited:
Code:
class IntList {
    final static int PLAIN    = 0;
    final static int EXTENDED = 1;
	
    IntCell first;
    IntCell last;

    IntList(IntCell f, IntCell l) {
       first = f;
       last  = l;
    }


    // Transform an array of integers into
    // a doubly-linked list of integers.
    public static IntList array2intList(int[] i) {
       for (int j=0; j<i.length; j++) {
		IntCell  = new IntCell(null, i[j], null);
	}
       return null;
    }

****More stuff should be here that is irrelevant i've just taken out***

    // Pretty Print a doubly-linked list.
    // Views: * PLAIN, e.g. [ 3, 4, 5 ]
    //        * EXTENDED, includes all references 
    public void printIntList(int view) {
    	if (view == EXTENDED) {
			System.out.print("FIRST: ");
			System.out.println(first);
			System.out.print("LAST: ");
			System.out.println(last);
			System.out.println();
		}
    	IntCell next = this.first;
    	boolean start = true;
		if (view == PLAIN) { 
			System.out.print("[ ");
		}
		
		while (next != null) {
			if (view == EXTENDED) {
				next.printIntCell();
			} else {
                if (!start) {
                    System.out.print(", ");
                }
				System.out.print(next.contents);
			}			
			start = false;
			next  = next.successor; 
       	}
		
		if (view == PLAIN) {
		    System.out.println(" ]");
		}
    }
}



package LinkedLists;
class IntCell {
    int     contents;
    IntCell predecessor;
    IntCell successor;

    IntCell(int i) {
       contents = i;
       predecessor = null;
       successor = null;
    }
    
    IntCell(IntCell p, int i, IntCell s) {
       contents = i;
       predecessor = p;
       successor = s;
    }
    
    public void printIntCell() {
	    System.out.print(contents);    
	    System.out.print(" : ( ");
	    
	    System.out.print(predecessor);    
	    System.out.print(" ) <---p--- ( ");
	    System.out.print(this);    
	    System.out.print(" ) ---s---> ( ");	    
		System.out.print(successor);
		
	    System.out.println(" )");  
	}
}
 
Right i think i've got it but i'm getting a null pointer exception when i try and pass it an array of intergers but i can't see why :(

Code:
public static IntList array2intList(int[] i) {
    	if (i.length == 0) {
            return new IntList(null, null);
        }
        else {
            IntCell first       = new IntCell(i[0]);
            IntCell current = first;
           
            for (int counter = 1; counter < i.length; counter++) {
                 IntCell next = new IntCell(current, i[counter], null);
                 current.successor = next;
                 next.predecessor  = current;
                 current = next;
            }
            return new IntList(first, current);
        }
    }

Any clues?
 
It works when I tested it with your code using a Main method:

Code:
    public static void main(String[] args) {
        int[] numbers = new int[] {1,2,3,4,5,6,7,8,9,10};
        IntList il = IntList.array2intList(numbers);
        il.printIntList(IntList.PLAIN);
    }

Output:

Code:
compile-single:
run-single:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
BUILD SUCCESSFUL (total time: 0 seconds)
 
Hmmm, i thought it should work, wtf, why do i seem to keep having problems!

Thats what i should be doing thought right, instead of using arrays? As the point in a doubly (and single) linked list is you can't straight access any cell (unlike an array).
 
Yeah you're are doing it right, I wasn't aware you were trying to create a linked structure until after your first couple of posts, I just thought it was some random method and some random classes. You need to keep track of the head (first), tail (last) and current elements as you construct the list so it looks like you are doing it correctly. Do you have the code that generated the NullPointerException?
 
hmmm it works now, not quite sure what was happening there and then but i may have corrupted objects when i was messing around with another method and the objects weren't being flushed from run to run i guess?
 
What i don't understand properly about these linked lists even though i have got it to work is how they know they're related to each other? I mean none of the objects have names, but i've pointed them to the successor and predecessor but then i make new objects with the same name? Are the references not by name and instead actual memory references the name just being a convenience? I'm slightly confused by this aspect...
 
Yeah, all of your objects exist in memory even though you don't have a named reference to them. You do in fact have a reference to them but it is stored inside another object, the actual way a linked structure works is that each object in the list (called a node) holds a reference to another object. The only way to traverse this structure is to visit each node and investigate it's child nodes until you come across a node with no children. You will often see recrusive functions when dealing with linked structures because they are quite efficient and performing operations on them.

Java uses something called a grabage collector to destroy objects that are no longer needed. The garbage collector will only destroy an object when it no longer has a reference to it (that is to say that there is no other object in existance that holds a reference to it).

It can be a confusing concept to understand at first, especially if you've only ever dealt with things like arrays before. The first time I encounter them I said "how can you create a collection from an object?" but I understood after actually using them. It is interesting to actually look at the source code behind the Java Collections and see how they work.
 
It is really cool, i've been playing around for the last hour now and i think i'm getting to grips with the whole concept properly, confused me a lot to begin with :) I've not thought of using recursive methods actually, thats an idea, i've just been using while or for loops to traverse them... We were told recursive things can be quite inefficient? Last semester we start Haskell from scratch to put us all on a level playing field, now that was weird, but its recursiveness was pretty cool, but now theyre telling us not to think like that, which is a bit strange. Are there any good java resources i should look at? I've got myself a pretty good cheat sheet or two which is nice, and learning how to use content assist in eclipse pretty efficiently, i just wonder if theres any thriving communities for beginners/novices like me to talk?
 
Recursion merely simplifies the code you have to write, it is typically slower then writing equivelant iterative code due to the extra time of loading and unloading on the stack, some languages are more streamlined for recursion but I don't know how the performance is.
 
Back
Top Bottom