0

Here is what I'm trying to do:

public class myClass
{
  int x;
  int y;
}

I have learned c++, so I tried to do this:

myClass [] a  = new myClass[5];
for(int i =0; i < 4; i++)
    a[i].x = 0;

This doesnt do anything, because all a[i] are null.

I know this is against the basic principal of Java, but there is a product called Alljoyn, which force me to do this, see:

https://www.alljoyn.org/docs-and-downloads/documentation/guide-alljoyn-development-using-java-sdk-rev-j#unique_28

AllJoyn doesnt allow constructor or other methods in the class. Is there any other way to initialize a pure struct?

user2184037
  • 1
  • 1
  • 2
  • Have you looked at: http://stackoverflow.com/questions/36701/struct-like-objects-in-java and http://stackoverflow.com/questions/5889034/how-to-initialize-an-array-of-objects-in-java? – PM 77-1 Mar 18 '13 at 21:04
  • Java graciously adds a default constructor to all classes that define no constructors at all. You can create instances of your `struct` class by calling `new myClass()`. – Perception Mar 18 '13 at 21:05

3 Answers3

5
  1. In Java there is no such thing as struct. What you presented is a class.
  2. As you observed a[i] is null, because references in your array are initialized to null. You haven't created any object yet. Use a[i] = new myClass() in your loop. This 0-argument constructor for class myClass will be generated by Java.
  3. Names of the classes in Java are written LikeThis by convention.
  4. a[i].x = 0 is useless. Read about primitive data types in Java. int fields are by default initialized to 0 by compiler.
  5. By doing i < 4 you don't initialize the last element (5th one). Better always do i < a.length.
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • I wouldn't call these "bad" C++ habits. Struct variable assignment is not a bad idea, it can be useful. – nmr Dec 12 '13 at 20:16
  • you have corrected the code. could you add what should OP do in Java, when [s]he conceptually attempts to "initialize struct instances"? – n611x007 Jul 08 '14 at 15:24
2

You are not initializing any object, try:

myClass [] a  = new myClass[5];
for(int i =0; i < 4; i++){
    a[i] = new myClass();
    a[i].x = 0;
}
igarcia
  • 691
  • 1
  • 9
  • 26
1

You need to first instialize all the myClass of your array:

myClass[] a  = new myClass[5];
for(int i =0; i < 4; i++) {
    a[i] = new MyClass();
    a[i].x = 0;
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118