Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple objects using for loop

Tags:

java

android

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

like image 668
artouiros Avatar asked Dec 06 '22 21:12

artouiros


2 Answers

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);
like image 69
Buhb Avatar answered Dec 10 '22 13:12

Buhb


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

like image 27
Iulius Curt Avatar answered Dec 10 '22 13:12

Iulius Curt