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?

2

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't call these "bad" C++ habits. Struct variable assignment is not a bad idea, it can be useful.
you have corrected the code. could you add what should OP do in Java, when [s]he conceptually attempts to "initialize struct instances"?
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;
}

Comments

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;
}

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.