ArrayList中返回所有条目的最后一个项目 [英] ArrayList returns last item for all entries

查看:262
本文介绍了ArrayList中返回所有条目的最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图填充对象一个ArrayList传递给ArrayAdapter(最终)。我已经拿出了一些code到一个小的测试项目来说明这个问题。

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.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

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

推荐答案

您需要让性别年龄非 - 静态,否则这些领域将只保留每类成员变量的单个值:

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命名惯例表明,变数开始的小写的信件使性别 性别

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

这篇关于ArrayList中返回所有条目的最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆