【问题标题】:Java - List of objects overwriting entrysJava - 覆盖条目的对象列表
【发布时间】:2018-05-02 05:16:18
【问题描述】:

我开始学习更多关于 Java 的知识并被困在这里: 想要制作包含值、索引和休息的对象,并在 main 方法中制作一个对象列表。 通过将新对象添加到列表中,之前的条目将被覆盖。

到目前为止,这是我的代码:

    public class LNGHW {

        public static int value;
        public static int index;
        public static int rest;

        public LNGHW(int val, int index, int mod) {
            this.value = val;
            this.index = index;
            this.rest = mod;
        }

        public static void main(String[] args) {
            ArrayList<LNGHW> items = new ArrayList<LNGHW>();

            items.add(new LNGHW(4, 0, 1));
            items.add(new LNGHW(2, 1, 1));

            System.out.println(items.get(0).getValue());
            System.out.println(items.get(1).getValue());
        }

        public int getValue() {
            return value;
        }

        public static void setValue(int value) {
            LNGHW.value = value;
        }

        public static int getIndex() {
            return index;
        }

        public static void setIndex(int index) {
            LNGHW.index = index;
        }

        public static int getRest() {
            return rest;
        }

        public static void setRest(int rest) {
            LNGHW.rest = rest;
        }
   }

我愿意接受各种帮助!

【问题讨论】:

  • 你的字段是 static 因此行为。从字段以及 getter/setter 中删除 static 修饰符,您应该一切顺利。

标签: java list object arraylist overwrite


【解决方案1】:
import java.util.*;
import java.lang.*;
import java.io.*;

 class LNGHW {
public  int value; /*made them  non-static*/
public  int index;
public  int rest;

public LNGHW(int val, int index, int mod) {
    this.value = val;
    this.index = index;
    this.rest = mod;
}

public static void main(String[] args) {
    ArrayList<LNGHW> items = new ArrayList<LNGHW>();

    items.add(new LNGHW(4, 0, 1));
    items.add(new LNGHW(2, 1, 1));

    System.out.println(items.get(0).getValue());
    System.out.println(items.get(1).getValue());
}

public int getValue() {
    return this.value;
}

public void setValue(int value) {      /*made these values non-static*/
    this.value = value;          /*set the values of object using **this**,not class name */
}

public int getIndex() {
    return this.index;
}

public void setIndex(int index) {
    this.index = index;
}

public int getRest() {
    return this.rest;
}

public  void setRest(int rest) {
    this.rest = rest;
}}

要了解它发生的原因,您需要了解 java 中的 staticnon-staticthis 关键字。请研究它们,然后您就会了解它们的区别。

STATIC--当我们希望类的每个对象的任何属性都相同时,我们使用 static 关键字。例如 - 假设有一个 MAN 类,并且很少有 agegender 等属性,那么不同对象的年龄会有所不同man 类,即 age 属性是对象级别的属性,因此它将是非静态的。而 MAN 类的每个对象的 gender 都是男性,因此它是一个类级别的属性,因此它应该是静态的。

最后,只要有类级属性,我们就使用静态变量,否则对于对象级属性,我们使用非静态变量。

我们使用 this 关键字来引用非静态变量,而 类名 用于引用静态变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多