ArrayList returns the last item for all records

I am trying to populate an ArrayList with objects to go to the ArrayAdapter (in the end). I lost some code in a small test project to illustrate the problem.

I have a class called "Rules" in which there are two members: "Gender and Age" (Rules.Java). In the MyArrayTest class, I instantiate the Rules objects and add them to the array_parts ArrayList. When I loop over the array, the loop executes the expected number of times, but duplicates the last element. Please can someone please indicate 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"); } } } 

The output is as follows:

Rules:

Female 22

Female 22

+4
source share
3 answers

You need to make Gender and Age not static , otherwise these fields save only one value for each member variable of the class:

 public String gender; public Integer age; 

In addition, Java naming conventions show that variables start with lowercase letters, creating a Gender Gender , etc.

+4
source

The problem is that your data members are static :

 public static String Gender; public static Integer Age; 

This means that they are shared by all instances of the class.

Remove the static keywords and you will be fine.

+3
source

The problem is the static variables in the rule class. Remove the static keyword. Static variables are set for each class. Therefore, it always takes the most recent value.

+1
source

All Articles