Useful Java Code Snippets 2 - Generic Methods



Looking for useful code examples to build your Java applications? 



Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. Here is an example:


/**
* Author : Berk Soysal
* UsefulCodes.java
*/

public class UsefulCodes {
  
  //Generic Methods with void return type ( for data types )
  
  public static <T> void generic(T[] x){
    for (T z : x)
      System.out.printf("%s ",z);
    
    System.out.println();
    
  }
  
  //Generic Methods with generic return type ( for data types )
  
  public static <T extends Comparable<T>> T generic2(T a, T b, T c){
    
    T max = a;
    
    if (b.compareTo(a) > 0)  max = b;
    
    if (c.compareTo(a) > 0) max = c;
    
    return(max); 
  }  
  
  // Main Method
  public static void main(String[] args) {
    String[] words={"funk","chunk","furry","terminator"};
    Integer[] numbers= {1,2,4,6,8};
    generic(words);
    generic(numbers);  
    
    System.out.println("Maximum value = " + generic2(422,1222,65));
    
  }
}


Please comment below if you have any questions. Thanks.
Continue Reading Useful Java Code Snippets 3 - Java Applets, JPanel, JFrame

Author:

Software Developer, Codemio Admin

Disqus Comments Loading..