8A52
8A52

Reputation: 793

Array of user defined objects in android

I created a class in a file called Pq which is an object having Strings like this

public class PQ {
    String ec;
    String com;
    String ai[3];
    String answers[3];
 }

Now I want to make an array of this object of length 10. Then fill each of the individual elements like ec,com with data as per my requirement with a for loop like

for(i=0;i<10;i++)
    pq.ec=25;

How to do this? I also want to fill ai,answers. How to access those elements I tried ArrayList but I am able to add the whole object but unable to add individual items Please help me out

Upvotes: 0

Views: 583

Answers (1)

Juvanis
Juvanis

Reputation: 25950

In your PQ class define getters and setters to manipulate fields of your objects safely conforming to the principle of encapsulation.

public String getEc ()
{
    return ec;
}

public void setEc ( String ec )
{
    this.ec = ec;
}

public String getCom ()
{
    return com;
}

public void setCom ( String com )
{
    this.com = com;
}

public String [] getAi ()
{
    return ai;
}

public void setAi ( String [] ai )
{
    this.ai = ai;
}

public String [] getAnswers ()
{
    return answers;
}

public void setAnswers ( String [] answers )
{
    this.answers = answers;
}

To populate an array of PQ objects use a code similar to this:

PQ [] objects = new PQ [ 10 ];

for ( int i = 0; i < objects.length; i++ )
{
    objects [ i ].setEc( "your ec" );
    objects [ i ].setCom( "your com" );
    objects [ i ].setAi( new String [] {"fill the string array"} );
    objects [ i ].setAnswers( new String [] {"fill the string array"} );
}

Note that you can fill each field of individual objects by using the appropriate setter method and valid argument(s).

Upvotes: 3

Related Questions