Java Tutorial/Generics/Generic Method

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating a Generic Method

public class MainClass {
  static <T, V extends T> boolean isIn(T x, V[] y) {
    for (int i = 0; i < y.length; i++){
      if (x.equals(y[i])){
        return true;
      }  
    }      
    return false;
  }
  public static void main(String args[]) {
    Integer nums[] = { 1, 2, 3, 4, 5 };
    if (isIn(2, nums)){
      System.out.println("2 is in nums");
    }
    if (!isIn(7, nums)){
      System.out.println("7 is not in nums");
    }
    // Use isIn() on Strings.
    String strs[] = { "one", "two", "three", "four", "five" };
    if (isIn("two", strs))
      System.out.println("two is in strs");
    if (!isIn("seven", strs))
      System.out.println("seven is not in strs");
  }
}



2 is in nums
7 is not in nums
two is in strs
seven is not in strs


Generic Constructors

class GenericClass {
  private double val;
  <T extends Number> GenericClass(T arg) {
    val = arg.doubleValue();
  }
  void showValue() {
    System.out.println("val: " + val);
  }
}
public class MainClass {
  public static void main(String args[]) {
    GenericClass test = new GenericClass(100);
    GenericClass test2 = new GenericClass(123.5F);
    test.showValue();
    test2.showValue();
  }
}



val: 100.0
val: 123.5


Generic method maximum returns the largest of three objects

public class MainClass {
  // determines the largest of three Comparable objects
  public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
    T max = x; // assume x is initially the largest
    if (y.rupareTo(max) > 0)
      max = y; // y is the largest so far
    if (z.rupareTo(max) > 0)
      max = z; // z is the largest
    return max; // returns the largest object
  } // end method maximum
  public static void main(String args[]) {
    System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
    System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6,
        8.8, 7.7));
    System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange", maximum(
        "pear", "apple", "orange"));
  }
}



Maximum of 3, 4 and 5 is 5
Maximum of 6.6, 8.8 and 7.7 is 8.8
Maximum of pear, apple and orange is pear


Generic methods: Max. Min

import java.util.Arrays;
import java.util.Collection;
import java.util.ruparator;
class Comparators {
  public static <T> T max(Collection<? extends T> coll, Comparator<? super T> cmp) {
    T candidate = coll.iterator().next();
    for (T elt : coll) {
      if (cmp.rupare(candidate, elt) < 0) {
        candidate = elt;
      }
    }
    return candidate;
  }
  public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll) {
    return max(coll, Comparators.<T> naturalOrder());
  }
  public static <T> T min(Collection<? extends T> coll, Comparator<? super T> cmp) {
    return max(coll, reverseOrder(cmp));
  }
  public static <T extends Comparable<? super T>> T min(Collection<? extends T> coll) {
    return max(coll, Comparators.<T> reverseOrder());
  }
  public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {
    return new Comparator<T>() {
      public int compare(T o1, T o2) {
        return o1.rupareTo(o2);
      }
    };
  }
  public static <T> Comparator<T> reverseOrder(final Comparator<T> cmp) {
    return new Comparator<T>() {
      public int compare(T o1, T o2) {
        return cmp.rupare(o2, o1);
      }
    };
  }
  public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {
    return new Comparator<T>() {
      public int compare(T o1, T o2) {
        return o2.rupareTo(o1);
      }
    };
  }

}
public class MainClass{
  public static void main(String[] args) {
    Comparator<String> sizeOrder = new Comparator<String>() {
      public int compare(String s1, String s2) {
        return s1.length() < s2.length() ? -1 : s1.length() > s2.length() ? 1 : s1.rupareTo(s2);
      }
    };
    Collection<String> strings = Arrays.asList("AAA", "aaa", "CCC", "f");
    
    System.out.println(Comparators.max(strings));
    System.out.println(Comparators.min(strings));
    System.out.println(Comparators.max(strings,sizeOrder));
    System.out.println(Comparators.min(strings,sizeOrder));
  }
}



f
AAA
aaa
f


Using generic methods to print array of different types

public class MainClass {
  // generic method printArray
  public static <E> void printArray(E[] inputArray) {
    // display array elements
    for (E element : inputArray)
      System.out.printf("%s ", element);
    System.out.println();
  }
  public static void main(String args[]) {
    // create arrays of Integer, Double and Character
    Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
    Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
    Character[] characterArray = { "H", "E", "L", "L", "O" };
    System.out.println("Array integerArray contains:");
    printArray(integerArray); // pass an Integer array
    System.out.println("\nArray doubleArray contains:");
    printArray(doubleArray); // pass a Double array
    System.out.println("\nArray characterArray contains:");
    printArray(characterArray); // pass a Character array
  } // end main
}



Array integerArray contains:
1 2 3 4 5 6 
Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 
Array characterArray contains:
H E L L O


Wildcard test program

import java.util.ArrayList;
public class MainClass {
  public static void main(String args[]) {
    Integer[] integers = { 1, 2, 3, 4, 5 };
    ArrayList<Integer> integerList = new ArrayList<Integer>();
    for (Integer element : integers)
      integerList.add(element);
    System.out.printf("integerList contains: %s\n", integerList);
    System.out.printf("Total of the elements in integerList: %.0f\n\n", sum(integerList));
    Double[] doubles = { 1.1, 3.3, 5.5 };
    ArrayList<Double> doubleList = new ArrayList<Double>();
    for (Double element : doubles)
      doubleList.add(element);
    System.out.printf("doubleList contains: %s\n", doubleList);
    System.out.printf("Total of the elements in doubleList: %.1f\n\n", sum(doubleList));
    Number[] numbers = { 1, 2.4, 3, 4.1 }; // Integers and Doubles
    ArrayList<Number> numberList = new ArrayList<Number>();
    for (Number element : numbers)
      numberList.add(element);
    System.out.printf("numberList contains: %s\n", numberList);
    System.out.printf("Total of the elements in numberList: %.1f\n", sum(numberList));
  }
  public static double sum(ArrayList<? extends Number> list) {
    double total = 0;
    for (Number element : list)
      total += element.doubleValue();
    return total;
  }
}



integerList contains: [1, 2, 3, 4, 5]
Total of the elements in integerList: 15
doubleList contains: [1.1, 3.3, 5.5]
Total of the elements in doubleList: 9.9
numberList contains: [1, 2.4, 3, 4.1]
Total of the elements in numberList: 10.5