我有几个关于如何设置类实例的问题。如果我有一个对象构造函数如下:
Object(String newName, ArrayList<Person> newPersonList){
name=newName;
personList=newPersonList;
System.out.println(personList);}
然后将其作为Object
类中的方法分配给某人:
matchPersonToObject(Person person){
this.matchedPerson=person;
person.addToObjects(this); //do I need to add the full project.domain address in here?
//Because if so it will only let me put the class `Person` in rather than an instance `person`
}
//in the person class:
addToObjects(Object obj){
this.objectList.add(obj);
System.out.println(objectList);
}
然后我按如下方式初始化:
Person chris=new Person("Chris");
Object obj1=new Object("thing",new ArrayList<Person>(Arrays.asList(chris)))
它输出:
[project.domain.Person@1a40fff] //personList in object constructor
[Object - null] //objectList once person has been matched to it
我的两个问题是 a)什么是给我个人实例的十六进制代码?为什么不只显示[project.domain.chris]? b)当我将对象添加到objectList时,为什么这个注册为null?我是否正确初始化了ArrayList?
答案 0 :(得分:0)
首先:永远不要用你正在使用的保留词来命名你的课程,例如:避免使用像Vector,Long等名称创建类...在代码中产生混淆。
第二:你正在查看的十六进制代码是你的类Person的哈希码,覆盖方法toString()os Person class。
public String toString() {
return <anything_you_want> + name;
}
可能导致包输入错误,因为你有一个带有Name对象的类,编译器无法识别你的类,java.lang.Object与你的Object类不同。