ArrayList 返回所有条目的最后一项 [英] ArrayList returns last item for all entries
问题描述
我试图用要传递给 ArrayAdapter 的对象填充 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.
我有一个名为 Rules 的类,它有两个成员,Gender 和 Age (Rules.Java).在 MyArrayTest 类中,我正在创建规则对象的实例并将它们添加到 rule_parts ArrayList.当我循环遍历数组时,循环执行预期的次数,但会复制最后一个元素.请有人指出原因.
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;
}
}
主类 - MyArrayTest.java
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");
}
}
}
输出如下:
规则:
女性22
女性22
推荐答案
你需要让 Gender
和 Age
非static
否则这些fields 将只保留每个类成员变量的一个值:
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;
旁白: Java 命名约定表明变量以 小写 字母开头,构成 Gender
gender
等
Aside: Java naming conventions indicate that variables start with lowercase letters making Gender
gender
, etc.
这篇关于ArrayList 返回所有条目的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!