-1

So I am using a foreach loop to create an array of object instances. So I have the constructor

Object[] instance = new Object[300],

And the foreach loop

for (Object i : instance)
{
    i = new Object(randParam1, randParam2);
    System.out.println("val " + i);
    System.out.println("stored " + instance[j]);
    j++;
}

(j has previously been initialized, randParam is short for a randomly declared parameter)

So I would expect this to go through each of the 300 instances in the array and declare random parameters to each. My print function "val" shows I do get a randomly generated instance each loop. However my print function "stored" returns null values, showing that every time the loop ends the values are declared null. Where am I going wrong? Thanks for any help and please correct me on any misused terminology.

To continue, I'll try to explain my goal. So I have the class "Object" which contains the constructor public Object(double dis, double ang, double diam, double sp, String col) { /accesses the constructor from the super class/ super(dis, ang, diam, sp, col); } In my main function I declare an array of 300 Object "instance". I then continue to use the for loop for (Object i : instance) i = new Object(randParam1, randParam2, etc...); The parameters are random values for dis, ang, diam and such. I am trying to assign all 300 instances with random values. I do achieve this as shown by my "Val" print function but the values are then wiped as shown by my "stored" function. The val and stored functions will not be in my final code.

1 Answers1

0

It looks like you are iterating through the items in the collection without assigning the value j to each item as the collection is immutable.

Take a look at this SF question - Java: adding elements to a collection during iteration

I'm not quite sure what you're trying to achieve but something like this example, which uses a second collection.

I'd guess something like:

Object[] instance = new Object[300];
Object[] instanceNew = new Object[300];

for (Object i : instance)
{
    instanceNew.Add(j)
    j++;
}

for (Object i : instanceNew)
{
    System.out.println("val " + i);
}
Community
  • 1
  • 1
nadsy
  • 144
  • 2
  • 8
  • The j value is just for bugtesting. My original code only contains i = new Object(randParam1, randParam2); What I don't understand is why my "val" and "stored" print functions do not have identical outputs – Aaron Hickman Oct 29 '16 at 13:27
  • taking a look at this: http://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration – nadsy Oct 29 '16 at 13:33
  • I'll try to explain my goal. So I have the class "Object" which contains the constructor – Aaron Hickman Oct 29 '16 at 13:45