Return to Snippet

Revision: 473
at July 15, 2006 02:54 by cetnar


Initial Code
public class NumberBox<N extends Number> extends Box<N> {



  public NumberBox( ) {

    super( );

  }

  

  // Sum everything in the box

  public double sum( ) {

    double total = 0;

    for (Iterator<N> i = contents.iterator( ); i.hasNext( ); ) {

      total = total + i.next( ).doubleValue( );

    }

    return total;

  }

}

You can use this same syntax in method definitions:

    public static double sum(Box<? extends Number> box1,

                             Box<? extends Number> box2) {

      double total = 0;

      for (Iterator<? extends Number> i = box1.contents.iterator( );

           i.hasNext( ); ) {

        total = total + i.next( ).doubleValue( );

      }

      for (Iterator<? extends Number> i = box2.contents.iterator( );

           i.hasNext( ); ) {

        total = total + i.next( ).doubleValue( );

      }

      return total;

    }

Initial URL


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

Initial Title
Generics - List of unknown - adding type restrictions.

Initial Tags


Initial Language
Java