Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 仅从列表中获取最后一个元素,而不考虑索引_Java_List - Fatal编程技术网

Java 仅从列表中获取最后一个元素,而不考虑索引

Java 仅从列表中获取最后一个元素,而不考虑索引,java,list,Java,List,我在显示使用Arrays实用程序类添加到列表中的元素时遇到问题。存储的值是如下所示的类中的对象 public class People { private static Integer age; private static String name; public People(String name,Integer age){ this.age = age; this.name = name; } public Integer getAge(){ return

我在显示使用Arrays实用程序类添加到列表中的元素时遇到问题。存储的值是如下所示的类中的对象

public class People {

private static Integer age;
private static String name;

public  People(String name,Integer age){

    this.age = age;
    this.name = name;
}

public Integer getAge(){
    return this.age;
}
public String getName(){
    return this.name;
}
@Override
public String toString(){
    return "name"+this.getName()+" Age"+ this.getAge();
}
}

通过以下代码将值添加到列表中:

   List<People> myPeople = Arrays.asList(

        new People("Samuel Owino", 18),
        new People("Swale Mdohe", 12),
        new People("Joseph Wambwile", 48),
        new People("Samuel Werre", 18),
        new People("Swale Mdohe", 12),
        new People("Joseph Wambwile", 48)
);

意识到问题在于对bean类、age和name中的实例变量使用static access修饰符,当static被删除时,该方法可以完美地工作。感谢您的引用。

您已将成员变量设置为静态变量,它们应为实例级别:

private Integer age;
private String name;
否则,对列表的每次添加都会覆盖
人员
对象的共享状态


我怀疑,当变量被传递到您要使用的构造函数中时,您的意思是使用
final
而不是
static

您将成员变量设置为static,它们应该是实例级别的:

private Integer age;
private String name;
否则,对列表的每次添加都会覆盖
人员
对象的共享状态


我猜想,当变量被传递到构造函数中,您打算使用
final
而不是
static

来获得列表的最后一项时,您可以执行以下操作:

System.out.println(myPeople.get(myPeople.size() - 1));

要获得列表的最后一项,可以执行以下操作:

System.out.println(myPeople.get(myPeople.size() - 1));

你到底有什么问题?你到底有什么问题?