Home > Back-end > Ask what's the difference between two kinds of generic methods.
Ask what's the difference between two kinds of generic methods.
Time:12-04
The following examples to look the same to achieve a goal,
Public class WildCardNeedDemo {
Public static void main (String [] args) { GenericStack IntStack=new GenericStack<> (a); IntStack. Push (1); IntStack. Push (2); IntStack. Push (2); System. The out. Println (" is the Max number is: "+ max1 (intStack)); System. The out. Println (" is the Max number is: "+ max2 (intStack)); }
Public static & lt; Type extends Number> Double max1 (GenericStack Stack) { Double Max=stack. Pop (). DoubleValue (); while (! Stack. The isEmpty ()) { Double value=(https://bbs.csdn.net/topics/stack.pop). DoubleValue (); If (value & gt; Max) { Max=value; } } The return of Max; }
Public static double max2 (GenericStack<? Extends Number> Stack) { Double Max=stack. Pop (). DoubleValue (); while (! Stack. The isEmpty ()) { Double value=(https://bbs.csdn.net/topics/stack.pop). DoubleValue (); If (value & gt; Max) { Max=value; } } The return of Max; } }
CodePudding user response:
In this case, you have no difference, because you don't use the type If you change to the following, however, there are difference between
public static & lt; Type extends Number> Type max1 (GenericStack Stack) {//the return value type to the type Double Max=stack. Pop (). DoubleValue (); while (! Stack. The isEmpty ()) { Double value=(https://bbs.csdn.net/topics/stack.pop). DoubleValue (); If (value & gt; Max) { Max=value; } } The return stack. Pop (); }
Public static Number max2 (GenericStack<? Extends Number> Stack) {//here you will find the return value of type cannot change to [?] , this is the difference between Double Max=stack. Pop (). DoubleValue (); while (! Stack. The isEmpty ()) { Double value=(https://bbs.csdn.net/topics/stack.pop). DoubleValue (); If (value & gt; Max) { Max=value; } } The return stack. Pop (); }