有什么用?在java中

sms*_*lce 6 java generics

我想知道使用的?在java泛型中.通过研究占位符T和通配符?,我想知道?,经历了几个网站/页面和书籍,但没有理解它.所以我创建了下面的课来研究差异.

import java.util.List;

public class Generics2 {

    public <T> void method1(List<T> list){
        System.out.println(list);
    }

    public <T extends Number> void method2(List<T> list){
        System.out.println(list);
    }

    /*public <T super Integer> void method3(List<T> list){

    }*///super does not work.

    public void method4(List<?> list){
        System.out.println(list);
    }

    public void method5(List<? extends Number> list){
        System.out.println(list);
    }

    public void method6(List<? super Integer> list){
        System.out.println(list);
    }

    public <T> void copy1(List<T> list1, List<T> list2){
        //copy elements from list1 to list2

    }//It does not span well with copy of one type of elements from list1 to other type elements in list2, where the list elements 
    //between the two are not same but are related through inheritance.

    public <T1,T2> void copy2(List<T1> list1,List<T2> list2){
        //copy elements from list1 to list2, right now we do not bother about the exceptions or errors that might generate.
    }//Our intention here is not to copy elements with relation between T1 and T2. We intend to explore the differences on T and ?

    public void copy3(List<?> list1,List<?> list2){
        //copy elements from list1 to list2, right now we do not bother about the exceptions or errors that might generate.
    }//Our intention here is not to copy elements with relation between T1 and T2. We intend to explore the differences on T

    public <T1 extends Object, T2 extends Object> void copy4(List<T1> list1, List<T2> list2){
        //copy elements from list1 to list2
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
Run Code Online (Sandbox Code Playgroud)

在一个案例中,我的班级可能会遗漏几个场景,所以我写的不完整,在这种情况下,任何人都可以帮助我实现更多场景.或者我找到了?作为冗余,除了它提供的功能,如在方法签名中使用超级关键字和较小字符以及返回类型.

编辑: 基本上我的问题是知道背后的原因,介绍的目的?通配符可以在任何地方替换它的通配符.这不是如何使用的问题?或T类型.当然,知道它的用法会提供一些答案.例如,我推断的事情:

  • ?使代码更具可读性,并且在某些地方不易编码
  • 它有时会减少代码膨胀.
  • 我们可以使用超类,这是T类型无法实现的.
  • 限制向列表添加新的随机元素.其中cast(没有classcastexception)有时对T类型有效.

还有吗?

Mar*_*oun 2

当列表(或集合)的类型未知时,可以使用无界通配符。

当您想要将值插入列表时,您永远不应该使用它(因为您可以插入的唯一值是null)。

当您想要获取有关某些数据结构的信息(例如打印其内容)时,当您不知道它可能包含什么类型时,可以使用它。例如:

public static void printList(List<?> list) {
    for (Object elem: list)
        System.out.print(elem + " ");
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)