Creating multiple objects using a loop

I want to create several view loops in a loop Example

for(int i =1; i<5; i++){
GridView view = new Gridview(this);
}

But it creates 5 gridview with the same name .. so in the future I can not set another option for a specific gridview. How can I get that the mesh created in the loop gets the form + i name

+3
source share
6 answers

Use list

List<GridView> views = new ArrayList<GridView>();
for(int i = 1; i < 5; i++) {
    views.add(new GridView(this));
}

Then you can get your views with

views.get(i);
+5
source

In addition, in your example, when the cycle loop ends for, the reference to this object is lost, because the area in which they were created remains. Without referring to objects, a garbage collector appears and frees this memory by deleting objects.

, . , , :

GridView view;
for(int i =1; i<5; i++){
    view = new Gridview(this);
}

, , . .

, , : , , - . .


. , ( ), . , Java, PHP:

class Object {
    function hello(){
        echo "Hello \n";
    }
}

for($i =1; $i<5; $i++){
    $name = "view".$i;
    $$name = new Object();
}

$view1->hello();
$view2->hello();
$view4->hello();

: http://codepad.org/bFqJggG0

+4

List GridViews.

List<GridView> grids = new ArrayList<GridView>();
for(int i =1; i<5; i++){
    grids.add(new Gridview(this));
}
+3

I think this code will create 5 GridViews, 4 of which will be available immediately for the Garbage Collection, since your code no longer refers to them.

If you create them in a loop, I think I will look for them in a data structure, such as a list or map, and then access them using an index or key.

+2
source

I think you can do something like this:

for(int i =1; i<5; i++){
GridView view = new Gridview(this);
view.setId(i);
}

and then you can distinguish all kinds

0
source
GridView[] view=new GridView[5];
for(int i=1;i<5;i++){
view[i]=new GridView(this);}

Now I think you can set the specified parameters.

0
source

All Articles