问题描述
我有一个练习,显然是在向我们询问基本概念。但是我找不到任何信息,或者至少我不确定我要搜索什么。所以我有一个小班级,我需要评论 3 个不同的构造函数。它看起来像这样:
class Person{
private String name;
private ArrayList<String> pseudos;
private String email;
//For me this one isn't a problem,it initialize a name & a mail with the two parameters and I believe the tricky part is this Array. I'm not sure but as far as I kNow it's okay to initialize the Array whithout getting him through parameter... Maybe I'm wrong.
public Person(String aName,String aEmail){
name = aName;
pseudos = new ArrayList<String>();
email = aMail;
}
//It seems to be the same explanation than the first one.
public Person(){
pseudos = newArrayList<String>();
}
//Apart from the uppercase I thinks this one is good,nothing is wrong.
public Person(String aName,String aMail,ArrayList<String> manyPseudos){
name = aName;
pseudos = new ArrayList<String>();
if(pseudos != null)
{
Pseudos.addAll(manyPseudos); //The uppercase here should be the problem
}
mail = aMail;
}
}
当然我试图通过我的课来弄清楚它,但我没有找到任何东西,所以我认为这是一个基于逻辑的练习......但我缺乏这种逻辑,我真的很想至少真正地理解这部分,因为它是非常基础的,我将不得不对其进行很多操作。
再次感谢您的指导和时间。
解决方法
我相信棘手的部分是这个数组。我不确定,但据我所知,在不让他通过参数的情况下初始化数组是可以的......也许我错了。
首先,pseudos
是一个 ArrayList
,而不是一个数组。这是两种不同的东西。
其次,pseudos
和其他变量一样是一个变量。这意味着您可以以与初始化任何变量相同的方式对其进行初始化:从另一个变量的值或直接从表达式。这里我们通过直接创建一个新的 pseudos
来初始化 ArrayList
。
Pseudos.addAll(manyPseudos); //这里的大写应该是问题
你的眼光不错。开头的 Psuedos
应该改为 pseudos
。由于 Java 区分大小写,因此这是两个不同的事情。我们通常使用类名以大写开头,变量和函数以小写开头的约定。从理论上讲,您可以拥有一个名为 Psuedos
的类和一个名为 pseudos
的变量,但您必须在脑海中将它们分开。