2016-05-24 147 views
0

我有問題顯示使用數組實用程序類添加到列表中的元素。值存儲是從下從列表中獲取最後一個元素不管索引

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) 
); 

顯示代碼如下:

myPeople.forEach(System.out::println); 

認識到問題是在實例變量上使用靜態訪問修飾符bean類,年齡和名稱,當靜態被移除時,該方法完美地工作。感謝您的參考。

+0

那麼究竟什麼是你遇到的問題? – jeffdill2

回答

1

爲了使您的列表的最後一個項目,你可以這樣做:

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

你有成員變量設置爲靜態的,他們應該是實例級別:

private Integer age; 
private String name; 

否則每次添加到列表覆蓋People對象的共享狀態。

我懷疑,因爲變量傳遞給構造函數,你的意思是使用final而不是static

相關問題