ArrayList returns last item for all entries
arraylist, java
Solution
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.
Problem
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