0

I am using Java SE on NetBeans 7.3.1.

I would like to form a Java array similar to the following in C

typedef struct sNewStruct{
    int min;
    int max;
} NewStruct;

NewStruct nsVar[19];

I tried the following

class IntRange{
    int min, max;    
}
IntRange[]  rangeNodes = new IntRange[19];

My problem is that, while rangeNodes is successfully allocated, all of its elements are nulls.

4
  • 2
    Loop over it and assign new IntRange() to every single one of them. Commented Sep 1, 2013 at 0:52
  • why would you think it should contain anything, you never set them to anything? Commented Sep 1, 2013 at 0:52
  • 1
    You can't really do the stack based allocation that C allows. It's unfortunate coming from C/C++, but that's how Java is. There are answers that show you what you must do. Commented Sep 1, 2013 at 0:54
  • 1
    @JarrodRoberson He would think that because that is how structs work in C/C++, an idea that has no analogue in Java. Commented Sep 1, 2013 at 1:00

2 Answers 2

4

That is how it should behave. Java isn't going to guess that the array should be filled with elements instantiated with the zero-argument constructor. If you want to fill the array, all you need to add is:

for (int i = 0; i < rangeNodes.length; i++)
    rangeNodes[i] = new IntRange();

You could explicitly initialize each element, but this is the cleanest solution.

Sign up to request clarification or add additional context in comments.

2 Comments

@JoshM Gotta be faster! :P
I was changing songs, will not happen again :)
2

As @ccKep is suggesting, you must assign a value to each element in the array:

for(int i = 0; i < rangeNodes.length; i++)
    rangeNodes[i] = new IntRange();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.