2016-12-26 50 views
1
List<Employee> empLList = new LinkedList<>(); 
     empLList.add(...) 
Iterator<Employee> descItr = empLList.descendingIterator(); 

在上面的代码我无法与以下错误无法访问子类方法,是泛型的缺点吗?或者我失去了一些东西

cannot find symbol 
    symbol: method descendingIterator() 
    location: variable empLList of type List<Employee> 

让我的descendingIterator有重铸empLList到链表

Iterator<Employee> descItr = ((LinkedList) empLList).descendingIterator(); 

我的问题访问的descendingIterator :一般来说,使用泛型的上述缺点是,即每次我们需要将对象转换回子类访问子类的方法,或者泛型应该像这样工作。

,或者我们不应该使用的情况下,仿制药,我们依靠太多的子类方法

还是我失去了一些东西

我很好奇在本例中使用泛型不是收藏用过的。

回答

1

这不是关于泛型。

查看API。 descendingIteratorDeque方法不List

LinkedList实现Deque

我的问题:一般情况下是使用泛型,即,每次我们需要转换的对象返回劣势以上subclasss访问子方法或泛型应该像这样工作。

您的片段错误与泛型概念无关。基于铸造的逻辑非常糟糕,应该通过修正设计来替代多态。

我很好奇GENERICS在示例中的使用而不是使用的集合。

然后问正确的问题。

更改为以下,使其工作:

Deque<Employee> empLList = new LinkedList<>(); 
empLList.add(...) 
Iterator<Employee> descItr = empLList.descendingIterator(); 
+0

感谢@Azodious ...顺便说一句,我没有倒下你 – cjava

0

这是因为仿制药的不是。这是因为,List中不存在descendingIterator()方法。在这一行

Iterator<Employee> descItr = empLList.descendingIterator(); 

您正在调用列表类型引用变量的方法。结果你得到编译错误。 当涉及到下面的线

Iterator<Employee> descItr = ((LinkedList) empLList).descendingIterator(); 

您铸造你的empList到链表和方法在LinkedList的可用它实现的Deque(的descendingIterator()的实施链表提供)

1

这有什么好与泛型相关。 List接口是一个契约,定义了它的所有实现必须提供的方法。有些像LinkedList可能会提供其他方法(例如前面提到的descendingIterator())。

您的员工列表被视为List的任何实施,因此所有List方法均可供使用,仅此而已。 如果你知道你的实现是LinkedList,你可以,但这是不好的做法。更好地保持其作为LinkedList则:

LinkedList<Employee> empLList = new LinkedList<>(); 
empLList.add(...) 
Iterator<Employee> descItr = empLList.descendingIterator(); 

...或者(如果你接受任何List,但希望使用descendingIterator()),创建一个新的LinkedList出来的:

List<Employee> empLList = ... // any implementation 
empLList.add(...) 
Iterator<Employee> descItr = new LinkedList(empLList).descendingIterator(); 
相关问题