【问题标题】:Creating an ArrayList of objects causes each element to be the same [duplicate]创建对象的ArrayList会导致每个元素相同[重复]
【发布时间】:2016-04-08 17:20:02
【问题描述】:

我是 Java 和 Android 新手。我正在编写的应用程序的一部分从文件中读取项目数据并在使用它填充 ListView 之前填充项目的 ArrayList。

来自 main.java:-

public class MainActivity extends AppCompatActivity {
    public static ArrayList<Item> items;
    .
    .
    .
    private void ReadItemsFile() throws IOException {

        File itemsFile = new File(itemsFilenameString);
        items = new ArrayList<Item>();

        try (BufferedReader itemsBufferedReader = new BufferedReader(new FileReader(itemsFile))) {
            for (String line; (line = itemsBufferedReader.readLine()) != null; ) {
                String[] lineStrings = line.split("\t|\n", 2);
                int itemNo = Integer.parseInt(lineStrings[0]);

                items.add(new Item(itemNo, lineStrings[1]));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

来自 Items.java:-

public class Item {
    private static int idInt;
    private static String description;
    private static Image image;

    public Item(int idInt, String description) {
         this.idInt = idInt;
         this.description = description;
         this.image = image;
    }
}

但是当我运行它时,我发现 ArrayList(和 ListView)充满了与从文件中读取的最后一个相同的项目。我试过调试这个,发现 ArrayList 中的所有项都更改为行后添加的最后一项:-

items.add(new Item(itemNo, lineStrings[1]));

请有人解释一下为什么会这样以及如何解决它?

我之前在此站点上检查过Creating an ArrayList of Objects,发现我的 ArrayList 填充方法与建议的相同。

【问题讨论】:

    标签: java android arraylist


    【解决方案1】:

    在您的 Item 类中,可以看到变量是 static 类型的,这可能是一个原因。尝试在这种情况下删除 static 关键字,这些变量/属性值依赖于对象,而不是对所有对象都通用

    public class Item {
        private int idInt;
        private String description;
        private Image image;
    
        public Item(int idInt, String description,Image image) {
             this.idInt = idInt;
             this.description = description;
             this.image = image;
        }
    

    希望这能解决您的问题..

    【讨论】:

    • 非常感谢。这解决了问题。
    【解决方案2】:

    我以前遇到过这个问题。当时我无法找到解决方案,所以我最终采取了不同的方法,即使用 SQLite 数据库将有关我的项目的信息存储在本地存储中。我不确定这对您有帮助,但它是在常规文件中存储数据的可行替代方案。

    【讨论】:

    • 这与他们的存储无关。他们的Item 类中显然有static 变量而不是实例变量。
    • 谢谢。我确实考虑过这条路线,但我现在意识到这是不必要的。
    【解决方案3】:

    Item 类中的字段使用static 会使它们属于该类,而不是该类的实例。 每次创建新项目时,都会将类字段重置为新值。您的 Item 对象没有声明任何特定于实例的数据。

    【讨论】:

    • 非常感谢。这解决了问题。
    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多