← 返回内容列表

Java泛型中<?>和<T>有什么区别?

Java泛型中<?>和<T>有什么区别?

?和T都表示不确定的类型 但如果是T的话 函数里面可以对T进行操作

<table cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <p>public static void printColl(ArrayList&lt;?&gt; al){<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Iterator&lt;?&gt; it = al.iterator();<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(it.hasNext())<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(it.next().toString());<br /> &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; }<br /> ?和T都表示不确定的类型&nbsp;&nbsp;但如果是T的话 函数里面可以对T进行操作 比如while里面可以这样写<br /> T t = it.next();<br /> System.out.println(t);</p> <p>T自定义泛型和?通配符泛型<br /> 1.在整个类中只有一处使用了泛型,使用时注意加了泛型了参数不能调用与参数类型有关的方法比如&ldquo;+&rdquo;,比如打印出任意参数化类型集合中的所有内容,就适合用通配符泛型&lt;?&gt;<br /> public static void printCollecton(Collection &lt;?&gt; collection)<br /> {<br /> for(Object obj: collection)<br /> {<br /> System.out.println(obj);<br /> }<br /> }<br /> 2. 当一个类型变脸用来表达两个参数之间或者参数与返回值之间的关系时,即统一各类型变量在方法签名的两处被使用,或者类型变量在方法体代码中也被使用而不仅 仅在签名的时候使用,这是应该用自定义泛型&lt;T&gt;。泛型方可以调用一些时间类型的方法。比如集合的add方法。<br /> public static &lt;T&gt; T autoConvertType(T obj)<br /> {<br /> &nbsp; &nbsp;&nbsp;&nbsp;return(T)obj;<br /> }</p> </td> </tr> </tbody> </table> <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td>泛型三种:<br /> &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; [1]ArrayList&lt;T&gt; al=new ArrayList&lt;T&gt;();指定集合元素只能是T类型<br /> &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; [2]ArrayList&lt;?&gt; al=new ArrayList&lt;?&gt;();集合元素可以是任意类型,这种没有意义,一般是方法中,只是为了说明用法<br /> &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; [3]ArrayList&lt;? extends E&gt; al=new ArrayList&lt;? extends E&gt;();<br /> &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;泛型的限定:<br /> &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;? extends E:接收E类型或者E的子类型。<br /> &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;?super E:接收E类型或者E的父类型。</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>以上就介绍了java泛型中T和?有什么区别,包括了两方面的内容,希望对其他编程教程有兴趣的朋友有所帮助。</p>

评论 (0)

加载评论中…