Java Generics通配符扩展了最终类 [英] Java Generics wildcard extends final class

查看:45
本文介绍了Java Generics通配符扩展了最终类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到 String class TestGenerics class 时不会发出任何警告>是 final ,并且不能扩展?

  import java.util.*;公共类TestGenerics {public void addStrings(List<?extended String> list){//这里有一些代码}}} 

解决方案

假设我有这样的方法:

 公共列表< ;?扩展T>filterOutNulls(列表T输入){... 

虽然不是世界上最好的签名,但仍然完全合法.如果我将 List< String> 传递给该方法会怎样?根据签名,它返回 List< ;?扩展String> .如果Java不允许该类型,则无法对 List< String> 使用此方法(或者至少不能使用返回值).

其次,在这种情况下, extends 语法仍然有用,因为 List< String> List< ;?扩展String> 有不同的限制-具体来说,您只能在 List< ;?之外添加 null 文字.扩展String> .我有时会使用吗?扩展以表示一个集合是只读的(因为您只能传递的 T null )和?超级表示只写(因为您只能以 Object 的形式获取 T s).这并不是绝对安全的方法(您仍然可以调用remove方法,传入 null s,向下转换等),但可以很容易地提醒您该集合的使用方式./p>

Why does Java doesn't throw any warning when compiling my TestGenerics class, considering that the String class is final and cannot be extended?

import java.util.*;
    public class TestGenerics { 
        public void addStrings(List<? extends String> list) {
          // some code here
        }
    }
}

解决方案

Let's say I had a method like this:

public List<? extends T> filterOutNulls(List<T> input) { ...

Granted, not the best signature in the world, but still perfectly legal. What would happen if I passed a List<String> to that method? According to the signature, it returns a List<? extends String>. If Java disallowed that type, it'd be impossible to use this method for List<String> (or at least, it'd be impossible to use the return value).

Secondarily, the extends syntax is still useful in this case, since List<String> and List<? extends String> have different restrictions -- specifically, you can't add anything but a null literal to List<? extends String>. I'll sometimes use ? extends to signify that a collection is read-only (since the only Ts you can pass in are null), and ? super to signify write-only (since you can only get out Ts as Object). This isn't completely fool-proof (you can still call remove methods, pass in nulls, downcast, etc) but serves as a gentle reminder of how the collection is probably meant to be used.

这篇关于Java Generics通配符扩展了最终类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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