0

I have a java code like below.

myclass a1 = new myclass(p1,p2);
myclass a2 = new myclass(p3,p4);

I want to do something like

myclass a[1] = new myclass(p1,p2);
myclass a[2] = new myclass(p3,p4);

how to do it ?

3
  • In c#? You are interested in having an array of custom objects, yes? Commented Nov 20, 2014 at 20:24
  • myclass[] a = new myclass[2]; and then a[0] = new myclass(p1, p2); a[1] = new myclass(p3, p4);. Commented Nov 20, 2014 at 20:27
  • just edited. The code is in Java @Kayaman will that work in Java ? Commented Nov 20, 2014 at 20:28

3 Answers 3

3
myclass[] myArray = new myclass[5];

myArray[0] = new myclass(p1,p3)

This is valid in java.

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

1 Comment

i think it should be myclass[] myArray = new myclass[5]; ?
1

Try this:

myclass[] a = new myclass[]{
    new myclass(p1,p2),
    new myclass(p1,p2)
};

Comments

1

it could be done in one line:

myclass[] myArray = myclass[]{ new myclass(p1, p2), new myclass(p3, p4) };

This is the same as:

myclass[] myArray = new myclass[2];
myArray[0] = new myclass(p1, p2);
myArray[1] = new myclass(p3, p4);

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.