Object 使用ArrayList和对象
这是我的对象类Object 使用ArrayList和对象,object,arraylist,Object,Arraylist,这是我的对象类 class Baller { public String name; public double height; public double weight; public String country; public Baller() { name = ""; height = 0; weight = 0; country = ""; } publi
class Baller
{
public String name;
public double height;
public double weight;
public String country;
public Baller()
{
name = "";
height = 0;
weight = 0;
country = "";
}
public Baller(String name1, double height1, double weight1, String country1)
{
}
public String getName()
{
return name;
}
public double getHeight()
{
return height;
}
public double getWeight()
{
return weight;
}
public String getCountry()
{
return country;
}
}
我需要创建一个arraylist,添加每个玩家的姓名、身高、体重和国家
我就是这样初始化它的:
ArrayList<Baller> playersNames = new ArrayList<>();
这就是我试图打印arraylist的方式
System.out.println("The roster is:"+playersNames);
当我把它打印出来时,上面写着:Baller@13bad12要输出名称,请使用:
System.out.println("The roster is:" + players.getName());
使用object需要知道的是,当您试图直接打印它们时,将调用toString()方法
对于Baller对象,未定义该对象,因此将打印引用。如果需要,可以覆盖它以输出名称:
@Override
public String toString()
{
return this.getName();
}
然后
System.out.println(“名册是:“+玩家”)代码>将起作用
编辑:要打印所有播放器值,只需将它们连接到返回字符串:
@Override
public String toString()
{
return "Name : " + this.getName() + ", Height : " + this.getHeight() + ", Weight : " + this.getWeight() + ", Country : " + this.getCountry();
}
有没有其他方法可以这样做,当我这样做的时候,它只会输出空值。我把它放在我的baller类的末尾,确保定义了名称。我看到你的带参数的构造函数什么都不做。如果返回null,则表示名称为null。为什么只打印名称?其他三个变量如何?然后将其他值连接到返回字符串。。我会编辑这篇文章。
@Override
public String toString()
{
return "Name : " + this.getName() + ", Height : " + this.getHeight() + ", Weight : " + this.getWeight() + ", Country : " + this.getCountry();
}