Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList returns last item for all entries [duplicate]

Tags:

java

arraylist

I am trying to populate an ArrayList with objects to pass to an ArrayAdapter (eventually). I have pulled out some code into a small test project to illustrate the issue.

I have a class called Rules which has two members, Gender and Age (Rules.Java). In the class MyArrayTest I am creating instances of Rules objects and adding them to the rule_parts ArrayList. When I loop over the Array the loop executes the expected number of times but duplicates the last element. Please could someone point out why.

Rules.Java

public class Rules {
public static String Gender;
public static Integer Age;


public Rules(String G, Integer C) {
//super();
    Gender = G;
    Age = C;
    }
}

Main Class - MyArrayTest.java

import java.util.ArrayList;


public class MyArrayTest {


private static ArrayList<Rules> rule_parts = new ArrayList<Rules>();

public static void main(String[] args) {


// Rules Array  
rule_parts.add(new Rules("Male",25));
rule_parts.add(new Rules("Female",22));

System.out.printf("\n\nRules:\n\n");
for (Rules r : rule_parts) {
    System.out.printf (r.Gender + "\n");
    System.out.printf(r.Age + "\n");


    }

}

}

Output is as follows:

Rules:

Female 22

Female 22

like image 393
Darnst Avatar asked Dec 27 '22 07:12

Darnst


1 Answers

You need to make Gender and Age non-static otherwise these fields will only retain a single value per class member variable:

public String gender;
public Integer age;

Aside: Java naming conventions indicate that variables start with lowercase letters making Gender gender, etc.

like image 137
Reimeus Avatar answered Jan 13 '23 04:01

Reimeus