当我创建另一个Class的ArrayList或TreeMap时,我只能引用最后添加或放置的元素。任何指针/解释/帮助都很受欢迎。
我是Java的新手(经过一段长时间的裁员后回到了它),但[可能是我的[代码]布局可辨别的]来自一个沉重的(主要是Visual)C ++背景。我正在尝试使用Java API,我已经多次使用C ++容器类...
好的,所以我想要一个类的ArrayList来定义一个人' ...
package arraylistcontainerprototype;
public class CPerson
{
private static String mForename;
private static String mSurname;
private static int mAge;
private static int mIndex;
// public Get/Set() methods encapsulated as normal (one example included but all follow the same code pattern)...
public String SetForename(mForename)
{
String oldForename = mForename;
this.mForename= mForename;
return oldForename;
}
public String GetForename()
{
return mForename;
}
}
然后我们在另一个'容器中使用它。上课,因此: - (请注意,此代码用于对方法进行原型设计,因为我的真实应用程序代码会遇到相同的问题。)
package arraylistcontainerprototype;
import java.util.ArrayList;
import arraylistcontainerprototype.CPerson;
public class CContainer
{
ArrayList<CPerson> mPersonArray = new ArrayList<CPerson>();
public int SetArray()
{
mPersonArray.clear();
for(int counter = 0; counter < 5; counter++)
{
CPerson person = new CPerson();
person.SetForename("Harry" + counter);
person.SetSurname("Royston" + counter);
person.SetAge(counter);
person.SetIndex(counter);
mPersonArray.add(person);
}
// then to test the array construction...
for(int counter = 0; counter < mPersonArray.size(); counter++)
{
CPerson person = mPersonArray.get(counter);
System.out.println(person + "; counter = " + counter);
System.out.println(person.GetForename() + "; counter = " + counter);
System.out.println(person.GetSurname() + "; counter = " + counter);
System.out.println(person.GetAge() + "; counter = " + counter);
System.out.println(person.GetIndex() + "; counter = " + counter);
}
}
}
main()中的代码驱动&#39;以上是: -
CContainer container = new CContainer();
container.SetArray();
The output generated is:-
arraylistcontainerprototype.CPerson@15db9742; counter = 0
Harry4; counter = 0
Royston4; counter = 0
4; counter = 0
4; counter = 0
arraylistcontainerprototype.CPerson@6d06d69c; counter = 1
Harry4; counter = 1
Royston4; counter = 1
4; counter = 1
4; counter = 1
arraylistcontainerprototype.CPerson@7852e922; counter = 2
Harry4; counter = 2
Royston4; counter = 2
4; counter = 2
4; counter = 2
arraylistcontainerprototype.CPerson@4e25154f; counter = 3
Harry4; counter = 3
Royston4; counter = 3
4; counter = 3
4; counter = 3
arraylistcontainerprototype.CPerson@70dea4e; counter = 4
Harry4; counter = 4
Royston4; counter = 4
4; counter = 4
4; counter = 4
BUILD SUCCESSFUL (total time: 0 seconds)
正如您所看到的,对CPerson类实例的引用似乎没问题但是对“getter”的调用是正确的。产生最后添加的&#39;元素的数据。
我在互联网上挖了一遍,在Stackoverflow中,但是看不出为什么这是行为不端。
任何指针都非常感激。非常感谢提前。 (如果您有意尝试,上面的代码应该很容易复制。我使用Netbeans,我在Windows10和Linux(Centos / Ubuntu)上得到相同的结果。