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");;
girl = new Girl[girl_count];

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

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


especially this line:

 girl = new Girl[girl_count];

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


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

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

    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

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(; //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(; //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 *