We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

cetnar on 07/15/06


Tagged

generics tiger unknown


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

xaviaracil


Generics - List of unknown - adding type restrictions.


Published in: Java 


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

  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 

You need to login to post a comment.