How to make an array list of objects in Java [closed]

Having this:

static class Girl{
    public String age;
    public String name;
    public String id;
}

static Girl[] girl;

Then i am unable to do this in my main function:

ResultSet r = s.executeQuery("select count(*) from children");   
r.next();
girl_count=r.getInt(1);
girl = new Girl[girl_count];

r = s.executeQuery("select * from children");   
int i = 0;
while(r.next()){
    i = r.getString("id");
    if(girl[i]==null)girl[i]=new Girl();
    girl[i].age=r.getString("age");
    girl[i].name=r.getString("name");
    girl[i].id=r.getString("id");
}

The above code is not working, what i would like to acheive is:

System.out.println(girl[3]);

especially this line:

 girl = new Girl[girl_count];

Can anyone help me correct this code ? – or find out what i’m missing here?

Answer

From the comment: you need a Map for what you want to achieve:

Map<Integer, Girl> girls = new HashMap<Integer, Girl>();

while(r.next()){
    int i = r.getInt("id"); // note the getInt()
    Girl g = girls.get(i); //attempt to get girl from map by ID, returns null if not found

    if(g==null) { // check if null
        g=new Girl(); // create
        girls.put(i,g); //put into map
    }
    g.age=r.getString("age");
    g.name=r.getString("name");
    g.id=r.getString("id");
}

And when you want to access the elements of the map:

Girl found = girls.get(id); //id is an Integer

To iterate over the Girl instances: Wow, did I just wrote what I wrote??? I have a wife!

for(Girl girl: girls.values()) {
   System.out.println(girl.name); //here you can do anything to the Girl, what morality permits...

}

Also, you can iterate over the keys by using the .keySet() method.

Or if you want the IDs too:

for(Map.Entry<Integer,Girl> entry: girls.entrySet()) {

   Integer id = entry.getKey();
   Girl girl = entry.getValue();
   System.out.println(girl.name); //here you can do anything to the Girl, what morality permits...

}

However the behaviour is that when there are more girls with the same id in the resultset (should not be possible anyway) it overwrites the attributes of said Girl, making it not deterministic…

Leave a Reply

Your email address will not be published. Required fields are marked *