artouiros
artouiros

Reputation: 3987

Creating multiple objects using for loop

What I want is to create multiple view in for 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 future i can't set different option to a specific gridview. How do I get, that gridivew created in a loop get view + i name

Upvotes: 4

Views: 33322

Answers (6)

Ritesh
Ritesh

Reputation: 326

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

Now I think you can set specified options.

Upvotes: 0

Iulius Curt
Iulius Curt

Reputation: 5114

Also, in your example, when a step of the for loop ends, the reference to that object is lost as the scope in which they were created is left. With no reference to the objects, the Garbage Collector comes in and frees that memory, deleting the objects.

So, you won't be able to access not even the last object created. If you modify the code like this, at the end of this code you will have only the last object instantiated:

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

Now the object exists in the scope you are in at the end of the code snippet. But only one object really exists.

So, the solution is to store the objects in some additional structure: an array if you know precisely how many objects you want, or some self dynamically allocated collection structure. And you have examples of both in the other answers.


Added: What you are actually asking for (to dynamically build the object's reference name) is called metaprogramming. I don't know if it is possible in Java, but here is an example of this done in 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();

Here is runnable code: http://codepad.org/bFqJggG0

Upvotes: 4

Buhb
Buhb

Reputation: 7149

Use a 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);

Upvotes: 6

DaveH
DaveH

Reputation: 7335

I think this code will create 5 GridViews, 4 of which will become immediately available for Garbage Collection as your code no longer has a reference to them.

If you create them in a loop, then I think I'd be looking to store them in a data structure such as a List or Map and then accessing them via an index or key.

Upvotes: 2

Houcine
Houcine

Reputation: 24181

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 difference between all views

Upvotes: 0

Haphazard
Haphazard

Reputation: 10948

Use a List of GridViews.

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

Upvotes: 3

Related Questions