java 通配符泛型,Java泛型与通配符

博客探讨了在Java中使用泛型时遇到的问题,即如何将一个实现了Animal接口的List转换为CollectionGeneric。文章指出由于类型安全的原因,直接转换会导致编译错误,并提出了解决方案,需要在GenericCollection类的setBeans方法中使用通配符来确保类型兼容。
摘要由CSDN通过智能技术生成

There is any way to fix this situation (I have try to simplyfy the scenario as much as i could):

public class Test {

public static void main(String[] args) {

/*

* HERE I would like to indicate that the CollectionGeneric can be of

* something that extends Animal (but the constructor doesn't allow

* wildcards)

*/

CollectionGeneric extends Animal> animalsCollectionGeneric = new CollectionGeneric();

List extends Animal> animals = getAnimals();

/* Why I cannt do that? */

animalsCollectionGeneric.setBeans(animals);

}

private static List extends Animal> getAnimals() {

return new ArrayList();

}

}

class CollectionGeneric {

private List beans;

public List getBeans() {

return (beans != null) ? beans : new ArrayList();

}

public void setBeans(List beans) {

this.beans = beans;

}

}

interface Animal {}

class Dog implements Animal{}

this scenario is giving me the next error:

The method setBeans(List) in the type

CollectionGeneric is not applicable for

the arguments (List)*

I am not sure about if there is a way to do this with generics,

解决方案

What this means is that the two collections can not be proved to have the same type bounds:

CollectionGeneric extends Animal> animalsCollectionGeneric =

new CollectionGeneric();

List extends Animal> animals = getAnimals()

The first one might at runtime have CollectionGeneric and the second one List. Mixing those would mean you lose the type safety ( not to mention the carnage ).

Therefore you need to prove to the compiler that those two are related, so your generic signatures should be:

public void setBeans(List extends T> beans) {}

public List getBeans();

and used as:

List extends Animal> beans = getBeans();

GenericCollection animals = new GenericCollection();

animals.add(beans);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值