结合使用Java中的方法和接收器类型中的通配符
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了结合使用Java中的方法和接收器类型中的通配符,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1886字,纯文字阅读大概需要3分钟。
内容图文
![结合使用Java中的方法和接收器类型中的通配符](/upload/InfoBanner/zyjiaocheng/775/688fe9487c6746bb8d1c2dff0af91d09.jpg)
我试图在接收器的类型和Java中的方法的参数类型中使用通配符的组合.上下文是定义容器的上下文.现在,类型Container不应该允许任何插入,因为此类型不指定包含的对象的类型.但是,如果底层数据结构允许,则应该有一种方法来搜索类型为T的对象,或者任何其他类型的对象.
这是一个演示此问题的代码段.关于如何在Java中实现这个设计目标的任何想法?
public class Main {
public static class Container<T extends Item> {
public void insert(T t) {
System.out.println("Inserting " + t);
}
public <R extends T> int find(R r) {
return r.hashCode();
}
}
public static class Item {
// Nothing here
}
public static class ExtendedItem extends Item {
// And nothing here...
}
public static class Client {
public static void main(String[] args) {
useContainerOfItem();
useContainerWildCardOfItem(new Container<Item>());
Container<? extends Item> c;
c = new Container<Item>(); // OK. type of c, is a super type of Container<Item>
c = new Container<ExtendedItem>(); // OK. type of c, is a super type of Container<ExtendedItem>
useContainerWildCardOfItem(c);
}
private static void useContainerOfItem() {
Container<Item> c = new Container<Item>();
c.insert(new Item()); // OK. We can insert items
c.insert(new ExtendedItem()); // OK. We can insert items
c.find(new Item()); // OK. We can find items in here.
c.find(new ExtendedItem()); // OK. We can also find derived items.
}
private static void useContainerWildCardOfItem(Container<? extends Item> c) {
c.insert(new Item()); // Error: expected. We should not be able to insert items.
c.insert(new ExtendedItem()); // Error: expected. We should not be able to insert anything!
c.find(new Item()); // Error. Why??? We should be able to find items in here.
c.find(new ExtendedItem()); // Error. Why??? We should be able to find items in here.
}
}
}
解决方法:
错误消息正在告诉您究竟是什么问题.你的find方法使用泛型R extends T,在这种情况下T是?,所以编译器无法检查你提供的R(一个Item)来检查它是否扩展了“capture#6-of?”.
内容总结
以上是互联网集市为您收集整理的结合使用Java中的方法和接收器类型中的通配符全部内容,希望文章能够帮你解决结合使用Java中的方法和接收器类型中的通配符所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。