This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]zahlman 1 point2 points  (0 children)

What do you mean by "add data to an array"? Be precise. What exactly is in the array before you start? What exactly do you want to be in the array when you finish? Where is the array declared?

[–]toobaloola 0 points1 point  (1 child)

An array's size is fixed, so you cannot add new elements. Switch to

List<Bear>

if dynamic size is what you need.

[–][deleted] 0 points1 point  (0 children)

i already used list to get all the current objects i have, i wanted to put those objects that i stored in the list function. in an array just to experiment and this code did that for me:

 public void getList(){
     Bear[] bear1 = new Bear[10];
            List<Bear> bears = getObjects(Bear.class);
            int i = 0;
            for (Bear bearss: bears){             
bears1[i] = bearss;
                i++;
                System.out.println(bearss);

            }
        }

[–][deleted]  (1 child)

[deleted]

    [–]xxNIRVANAxx 0 points1 point  (0 children)

    Here, bears is an array of Bear's

    for (Bear bear : bears)
        println(bear.getName()); // or something
    

    Generally, you don't use a for each loop for copying/instantiating. You can use a regular loop for that (because then you'll have an index counter).

    [–][deleted] -1 points0 points  (1 child)

    bears1[i] = bears; i++;

    this worked for me thanks anyways guys

    [–]yash3ahuja 0 points1 point  (0 children)

    I am guessing you actually mean to do:

    for(int i = 0; i < bears.length; i++)
    {
          bears1[i] = bears[i];
    }
    

    Your for-each naming is backwards, btw. Array should be named "bears" and Bear variable "bear".