将对象投射到< T>型 [英] Casting Objects to <T>-type
问题描述
我将List接口实现为将数据存储在< T>
类型数组中的类。由于集合将对象存储为 Object
,所以这引发了将Collection作为参数的方法的问题。我如何将 Object
转换为 T
?简单转换不起作用。
class MyCollection< T>实现List< T> {
T [] tab;
MyCollection(){
this.tab =(T [])new Object [10];
public boolean addAll(Collection c){
for(Object o:c){
o =(T)o;
for(int i = 0; i< tab.length; i ++){
tab [i] = o;
}
}
}
}
$ p $ public boolean addAll(Collection< ;? extends T> c)
但失败:
public boolean retainAll(Collection <?> c)
,因为我无法在这里更改Collection类型:/ b /
public boolean retainAll(Collection<?> c){
布尔结果= false; (T t:c){
}
返回结果为
;
}
这是正确的做法吗?
是的,那是正确的做法。这就是界面的定义(除了界面使用 E
,但没关系)。
<请注意,你的
addAll
应该返回一个布尔值
。此外,你不需要投入你已经实现的 addAll
。改变你的循环: for(T o:c){...}
并且您的 retainAll
应该也可以,只要您返回 boolean
。
编辑:
$ c> retainAll 实现,不需要遍历传入的集合<>
并转换为 T
。考虑迭代选项卡
支持数组,并查看每个实例是否包含在传入的 Collection <?>> ç
。如果由于某种原因,您绝对需要使用 c
中的项目作为 T
s,您可以投射。
I'm implementing List interface to a class which stores data in a <T>
type array. This raises problems with methods that take Collection as parameters, since collection stores it's objects as Object
. How can I transform Object
to T
? Simple casting doesn't work.
class MyCollection<T> implements List<T>{
T[] tab;
MyCollection() {
this.tab = (T[])new Object[10];
}
public boolean addAll(Collection c){
for(Object o : c){
o = (T)o;
for(int i = 0; i < tab.length; i++){
tab[i] = o;
}
}
}
}
I'm trying :
public boolean addAll(Collection<? extends T> c)
but it fails with :
public boolean retainAll(Collection<?> c)
since I cannot change the Collection type here :/
public boolean retainAll(Collection<?> c){
boolean result = false;
for(T t : c){
}
return result;
}
Is it the right approach ?
Yes, that is correct approach. That is what the interface is defined as (except that the interface uses E
, but that doesn't matter).
Note that your addAll
should return a boolean
. Also, you dont need to cast in addAll
that you have implemented. Change your loop instead:
for(T o : c){...}
And your retainAll
should be fine as well, as long as you return a boolean
.
EDIT:
For your retainAll
implementation, there shouldn't be a need to iterate over the passed in Collection<?>
and cast to a T
. Consider iterating over your tab
backing array and seeing if each instance is contained in the passed in Collection<?> c
. If for some reason you absolutely need to use the items within c
as T
s, you can cast.
这篇关于将对象投射到< T>型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!