generic interface

--Main--------------------------------------------
package pkg.y2009.m06.test002;

public class Main {

/**
* generic interface
* @param args
*/
public static void main(String[] args) {
Integer[] integers = {8, 7, 6, 5, 12, 11, 10};
Character[] characters = {'a', 's', 'd', 'f', 'g'};
MinMaxImpl i = new MinMaxImpl(integers);
MinMaxImpl c = new MinMaxImpl(characters);

System.out.println("integers.min: " + i.min());
System.out.println("integers.max: " + i.max());
System.out.println("characters.min: " + c.min());
System.out.println("characters.max: " + c.max());
}
}
--/Main-------------------------------------------
--MinMax------------------------------------------
package pkg.y2009.m06.test002;

public interface MinMax <'T extends Comparable<'T>> {
  T min();
  T max();
}
--/MinMax-----------------------------------------
--MinMaxImpl--------------------------------------
package pkg.y2009.m06.test002;

public class MinMaxImpl<'T extends Comparable<'T>> implements MinMax<'T> {
  T[] vals;
  MinMaxImpl(T[] ts) { vals = ts; }
  public T min() {
    T min = vals[0];
    for (T t : vals)
      if (t.compareTo(min) < 0) min = t;
    return min;
  }
  public T max() {
    T max = vals[0];
    for (T t : vals)
      if (t.compareTo(max) > 0) max = t;
    return max;
  }
}
--/MinMaxImpl-------------------------------------
--console log-------------------------------------
integers.min: 5
integers.max: 12
characters.min: a
characters.max: s
--/console log------------------------------------

ref:
http://www.java2s.com/Code/Java/Language-Basics/Agenericinterfaceexample.htm
2009-06-22 02:13 : __lang__java : コメント : 0 : トラックバック : 0 :
コメントの投稿
非公開コメント

« next  ホーム  prev »

search

ad



counter


tag cloud

category cloud