2017-08-12 31 views
0

在一个Android应用程序中,我制作了一个我创建的某个类的实例的数组,然后在该程序中,我需要使用该类中的getter和setter方法来处理该数组中的类的实例。我是否需要将数组中的类的实例分配给新的类初始化程序?下面是一些代码来清除此设置:如何将数组中的类的实例分配给java中的类初始化程序?

public class ProfileInformation { 

    private String console; 
    private String gamertag; 

    public String getConsole() { 
    return console; 
    } 

    public void setConsole(String console) { 
    this.console = console; 
    } 

    public String getGamertag() { 
    return gamertag; 
    } 

    public void setGamertag(String gamertag) { 
    this.gamertag = gamertag; 
    } 
} 

阵列

ArrayList<ProfileInformation> ProfTags = new ArrayList<>(); 

ProfileInformation的一些实例,然后添加到ArrayList中,然后我得到的一个来自arraylist的实例并尝试使用getGamertag()将其设置为字符串:

ProfileInformation profNew = ProfTags.get(ProfTags.size()-1); 
String example = profNew.getGamertag(); 

问题是例子将等于null。为什么是这样?

+0

向我们展示如何添加东西? –

+1

此外,这不是特定于Android的 – SuperStormer

+0

对于愚蠢的问题抱歉,但你真的设置“gamertag”值吗? – FonzTech

回答

0

首先,Arraylist是一个列表,尽量不要将它与实际数组混淆。

我是否需要将该类的实例从数组中分配给新的类初始化程序?

你不需要从Arraylist中得到一个元素,没有。你可以连续使用很多方法一起

String example = ProfTags.get(ProfTags.size()-1).getGamertag(); 

例如将等于空。为什么是这样?

出于同样的原因,任何对象为空......你永远不会将其设置为别的

0

此代码在我的笔记本上运行:

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

    element = new ProfileInformation(); 
    element.setGamertag("Actual Gamer tag value"); 

    ProfTags.add(element); 

    ProfileInformation profNew = ProfTags.get(ProfTags.size()-1); 
    String example = profNew.getGamertag(); 
} 

输出是:

我想你没有打电话setGamertag(String)

相关问题