Generics - List of unknown - adding type restrictions.


/ Published in: Java
Save to your folder(s)

Za typ N można podstawić dowolny typ dziedziczący po Number.


Copy this code and paste it in your HTML
  1. public class NumberBox<N extends Number> extends Box<N> {
  2.  
  3.  
  4.  
  5. public NumberBox( ) {
  6.  
  7. super( );
  8.  
  9. }
  10.  
  11.  
  12.  
  13. // Sum everything in the box
  14.  
  15. public double sum( ) {
  16.  
  17. double total = 0;
  18.  
  19. for (Iterator<N> i = contents.iterator( ); i.hasNext( ); ) {
  20.  
  21. total = total + i.next( ).doubleValue( );
  22.  
  23. }
  24.  
  25. return total;
  26.  
  27. }
  28.  
  29. }
  30.  
  31. You can use this same syntax in method definitions:
  32.  
  33. public static double sum(Box<? extends Number> box1,
  34.  
  35. Box<? extends Number> box2) {
  36.  
  37. double total = 0;
  38.  
  39. for (Iterator<? extends Number> i = box1.contents.iterator( );
  40.  
  41. i.hasNext( ); ) {
  42.  
  43. total = total + i.next( ).doubleValue( );
  44.  
  45. }
  46.  
  47. for (Iterator<? extends Number> i = box2.contents.iterator( );
  48.  
  49. i.hasNext( ); ) {
  50.  
  51. total = total + i.next( ).doubleValue( );
  52.  
  53. }
  54.  
  55. return total;
  56.  
  57. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.