class Person{
private String navn; //a Person class, "navn" means "name" in norwegian
Person(String s){
navn = s;
}
public String hentNavn(){ //returns the name of the person
return navn;
}
}
class PersonBeholder<Person>{ //a container using an own implementation of
private Lelem forste; //a linked list
private int ant = 0; //number of persons currently in the list
private class Lelem{
Lelem neste;
Person personen;
Lelem(Person p){
personen = p;
}
public Person hentPerson(){ //returns the Person object
return personen; //being pointed to
}
}
public void settInnPerson(Person denne){ //this is the method for
Lelem lel = new Lelem(denne); //appending a Person to the list
lel.neste = forste;
forste = lel;
**System.out.println(forste.hentPerson().hentNavn());**
/*this is where it goes wrong*/
ant++;
}
}
class TestPersoner2{
public static void main (String [ ] args){
PersonBeholder<Person> pl = new PersonBeholder<Person>();
Person Emil = new Person("Emil");
Person Nils = new Person("Nils");
pl.settInnPerson(Emil);
pl.settInnPerson(Nils);
}
}
输出
TestPersoner2.java:35: error: cannot find symbol
System.out.println(forste.hentPerson().hentNavn());
^
symbol: method hentNavn()
location: class Object
1 error
试图让 java 打印存储在容器中的人的姓名,该容器具有自己的链表数据结构实现。
我创建了一个自己的列表元素类,用于为每个元素创建指向列表中下一个元素的对象。Lelem(列表元素)类包含一个返回 Person 对象的方法,而 Person 类包含一个返回字符串“navn”的方法,该字符串是人名。
Java 似乎认为这个 hentNavn() 方法不存在,我不明白为什么。有人可以告诉我这只是一个愚蠢的错字吗?
乙