如何访问存在于linkedlist集合中的对象的实例变量?

时间:2013-10-27 12:26:30

标签: java generics collections

我正致力于收藏品和仿制品。在我的任务中,我必须将一个人对象存储到链表列表集合中。然后我必须将人的年龄与我给出的价值进行比较。但我无法访问存储在链表中的对象变量。

这是我的代码:

class person {
    int age;
    person(int a)
    {
       age = a;
    }
    public int getAge()
    {
         return age;
    }
}

class myList<E>
{
  LinkedList<E> list;
  myList()
  {
    list = new LinkedList<E>();
  }
  void addElement(Person p){}
  void removeElement(int index){}
  boolean compareAge(int age){
       for(E p : list){
             int a = p.getAge();
             if(a.equals(age))
             {
                return true;
             }
             else{
                return false;
             }
       }
  }

}

但是,我收到的错误是: 错误:找不到符号     p.getAge();                                   ^   符号:方法get(int)   location:类型E的变量值   其中E是一个类型变量:     E扩展了类myList

中声明的Object

4 个答案:

答案 0 :(得分:1)

您的代码说“请使用任何类型的List,将其称为E”。然后,您会在代码中强制使用E的假设,这不起作用,因为E可以任何

您需要删除通用声明,以便拥有List<person>。或者,您可以限制List仅限person或其子女:

class myList<E extends person>

注意

请使用Java命名约定,类在UpperCamelCase中。

答案 1 :(得分:0)

E是通用类型。 由于您事先已经知道了要存储在列表中的类型,因此您的文件应该是:

class myList
{
  LinkedList< person > list;

...

答案 2 :(得分:0)

您应该使用:

class myList<E extends Person>

此外,您还必须解决其他一些问题(等于int,以及类Person上的'p'。

答案 3 :(得分:0)

而不是E你应该有人。 链表清单......
但是我认为全班通用并不重要。
DOCUMENTATION to the list