Array of references

Y

Yan

Hi.

I have plenty of experiance in C/C++, but this Java no-pointer policy
is driving me crazy. I want to create an array of references - what
would be an array of pointers in C.
I try to do the following:

JTree[] trees = new JTree[2];
....
JTree tree1 = new JTree();
JTree tree2 = new JTree();


I already have 2 trees and I want to reference them using the array,
so I do:

trees[0] = tree1;
trees[1] = tree2;

but when I try to access trees[0], for example I get a null pointer
exception. How can I do this stuff.

Thank you in advance
Yan
 
G

Gordon Beaton

I have plenty of experiance in C/C++, but this Java no-pointer
policy is driving me crazy. I want to create an array of references
- what would be an array of pointers in C. I try to do the
following:

JTree[] trees = new JTree[2];
...
JTree tree1 = new JTree();
JTree tree2 = new JTree();


I already have 2 trees and I want to reference them using the array,
so I do:

trees[0] = tree1;
trees[1] = tree2;

So far so good.
but when I try to access trees[0], for example I get a null pointer
exception. How can I do this stuff.

There's nothing wrong with the few lines of code you've posted. Your
problem is due to something else.

Show a complete example that has the problem you describe.

/gordon
 
A

ak

Yep, your code seems ok.

you can do also following:

JTree[] trees = new JTree[count];
for(int i = 0; i < count; i++) {
trees = new JTree();
}
 
Y

Yan

Sorry.

Got the problem - it was somewhere else. I'm using 1 tree model and 2 views
in different tabs, so I need to know which tab I am in right now, so the
current tree pointer wasn't initialized in the right place.

thanx
Yan
 
D

Darren

The following works fine for me, I'd say you have another mistake in
your code.


import javax.swing.JTree;

public class Test {

public static void main( String[] args ) {
JTree[] trees = new JTree[2];
JTree tree1 = new JTree();
JTree tree2 = new JTree();

trees[0] = tree1;
trees[1] = tree2;

System.out.println( trees[0] );
System.out.println( trees[1] );
}

}
 
D

Darryl L. Pierce

Yan said:
I already have 2 trees and I want to reference them using the array,
so I do:

trees[0] = tree1;
trees[1] = tree2;

but when I try to access trees[0], for example I get a null pointer
exception. How can I do this stuff.

Are you initializing the reference in trees[0]? Unlike in C++, Java does
not initialize the elements of an array of object references.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top