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

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

问题描述

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



所以有什么区别:

  HashMap< String,?> HASH1; 

  HashMap< String,Object> HASH2; 


解决方案

HashMap< String,String> 匹配 Map< String,?> 但不是 Map< String,Object> 。假设你想写一个方法接受从 String s到任何地方的映射:如果你要写

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

你不能提供 HashMap< String,String> 。如果你写了

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

$ / code>

有用!

在Java的泛型中有时会被误解的事情是 List< String> 不是 List< Object> 的子类型。 (但是 String [] 实际上是 Object [] 的子类型,这就是泛型和数组的原因之一不能混合使用(Java中的数组是协变的,泛型不是,它们是不变的))。 b如果你想写一个方法来接受 List > InputStream s和<$ c $的子类型c> InputStream ,你会写出:

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

顺便说一下:当你想了解Java中不那么简单的东西时,Joshua Bloch的Effective Java 是一个很好的资源。 (上面的问题在本书中也有详细介绍。)


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 '?'.

So what's the difference between:

HashMap<String, ?> hash1;

and

HashMap<String, Object> hash2;

解决方案

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) {
    ...
}

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

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

it works!

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)).

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) {
    ...
}

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天全站免登陆