「Java」メソッドにジェネリクス(Generics)を使用する

環境
JDK1.8
Eclipse 2019

書式
private static <T> T メソッド名(T tt) {
処理コード
}
メソッドにジェネリクスを使用する場合、戻り値(T)の前にジェネリクス(<T>)を記述します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.Test;
public class TmethodDemo {
public static void main(String[] args) {
//引数にString型を指定
String resA = getFunc("study skill");
//引数にInteger型を指定
Integer resB = getFunc(123);
//引数にDouble型を指定
Double resC = getFunc(98.65);
System.out.println(resA);
System.out.println(resB);
System.out.println(resC);
}
// メソッドにジェネリクスを使用
private static <T> T getFunc(T tt) {
return tt;
}
}
package com.arkgame.Test; public class TmethodDemo { public static void main(String[] args) { //引数にString型を指定 String resA = getFunc("study skill"); //引数にInteger型を指定 Integer resB = getFunc(123); //引数にDouble型を指定 Double resC = getFunc(98.65); System.out.println(resA); System.out.println(resB); System.out.println(resC); } // メソッドにジェネリクスを使用 private static <T> T getFunc(T tt) { return tt; } }
package com.arkgame.Test;

public class TmethodDemo {

      public static void main(String[] args) {
            //引数にString型を指定
            String resA = getFunc("study skill");
            
            //引数にInteger型を指定
            Integer resB = getFunc(123);
            
            //引数にDouble型を指定
            Double resC = getFunc(98.65);
            
            System.out.println(resA);
            System.out.println(resB);
            System.out.println(resC);
      }

      // メソッドにジェネリクスを使用
      private static <T> T getFunc(T tt) {
            return tt;
      }
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
study skill
123
98.65
study skill 123 98.65
study skill
123
98.65

 

Java

Posted by arkgame