之间有什么区别?和 Java 泛型中的对象? [英] What is the difference between ? and Object in Java generics?

查看:27
本文介绍了之间有什么区别?和 Java 泛型中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Eclipse 来帮助我清理一些代码以正确使用 Java 泛型.大多数情况下,它在推断类型方面做得非常出色,但在某些情况下,推断类型必须尽可能通用:Object.但是 Eclipse 似乎给了我一个选项,可以在 Object 类型和 '?' 类型之间进行选择.

I'm using Eclipse to help me clean up some code to use Java generics properly. Most of the time it's doing an excellent job of inferring types, but there are some cases where the inferred type has to be as generic as possible: Object. But Eclipse seems to be giving me an option to choose between a type of Object and a type of '?'.

那么两者有什么区别:

HashMap<String, ?> hash1;

HashMap<String, Object> hash2;

推荐答案

HashMap 的一个实例匹配 Map 但不匹配映射<字符串,对象>.假设你想写一个方法来接受从 Strings 到任何东西的映射:如果你写

An instance of HashMap<String, String> matches Map<String, ?> but not Map<String, Object>. Say you want to write a method that accepts maps from Strings to anything: If you would write

public void foobar(Map<String, Object> ms) {
    ...
}

您不能提供 HashMap.如果你写

you can't supply a HashMap<String, String>. If you write

public void foobar(Map<String, ?> ms) {
    ...
}

它有效!

Java 泛型中有时会被误解的一件事是 List 不是 List 的子类型.(但 String[] 实际上是 Object[] 的子类型,这就是泛型和数组不能很好混合的原因之一.(Java 中的数组是协变的,泛型不是,它们不变))

A thing sometimes misunderstood in Java's generics is that List<String> is not a subtype of List<Object>. (But String[] is in fact a subtype of Object[], that's one of the reasons why generics and arrays don't mix well. (arrays in Java are covariant, generics are not, they are invariant)).

示例:如果您想编写一个接受 InputStreamListInputStream 的子类型的方法,您可以编写

Sample: If you'd like to write a method that accepts Lists of InputStreams and subtypes of InputStream, you'd write

public void foobar(List<? extends InputStream> ms) {
    ...
}

顺便说一句:Joshua Bloch 的 Effective Java当您想了解 Java 中不那么简单的事情时,这是一个很好的资源.(你上面的问题在书中也有很好的介绍.)

By the way: Joshua Bloch's Effective Java is an excellent resource when you'd like to understand the not so simple things in Java. (Your question above is also covered very well in the book.)

这篇关于之间有什么区别?和 Java 泛型中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆