「Java」総称型(Generics)を使うサンプル

2021年4月6日

書式
class クラス名<T>
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.study.arkgame;
//総称型 DemoInfoの定義
class DemoInfo<T> {
private T tm;
public DemoInfo(T val) {
this.tm = val;
}
public T getValue() {
return tm;
}
}
public class Ttype {
// mainクラス
public static void main(String[] args) {
// Integer型
DemoInfo<Integer> cftA = new DemoInfo<Integer>(12345);
Integer resA = cftA.getValue();
System.out.println("Integer型ジェネリクス: " + resA);
// Double型
DemoInfo<Double> cftD = new DemoInfo<Double>(23.56d);
Double resD = cftD.getValue();
System.out.println("Double型ジェネリクス: " + resD);
// String型
DemoInfo<String> cftB = new DemoInfo<String>("this is a test");
String resC = cftB.getValue();
System.out.println("String型ジェネリクス: " + resC);
}
}
package com.study.arkgame; //総称型 DemoInfoの定義 class DemoInfo<T> { private T tm; public DemoInfo(T val) { this.tm = val; } public T getValue() { return tm; } } public class Ttype { // mainクラス public static void main(String[] args) { // Integer型 DemoInfo<Integer> cftA = new DemoInfo<Integer>(12345); Integer resA = cftA.getValue(); System.out.println("Integer型ジェネリクス: " + resA); // Double型 DemoInfo<Double> cftD = new DemoInfo<Double>(23.56d); Double resD = cftD.getValue(); System.out.println("Double型ジェネリクス: " + resD); // String型 DemoInfo<String> cftB = new DemoInfo<String>("this is a test"); String resC = cftB.getValue(); System.out.println("String型ジェネリクス: " + resC); } }
package com.study.arkgame;

//総称型 DemoInfoの定義
class DemoInfo<T> {
      private T tm;

      public DemoInfo(T val) {
            this.tm = val;
      }

      public T getValue() {
            return tm;
      }
}

public class Ttype {
      // mainクラス
      public static void main(String[] args) {
            // Integer型
            DemoInfo<Integer> cftA = new DemoInfo<Integer>(12345);
            Integer resA = cftA.getValue();
            System.out.println("Integer型ジェネリクス: " + resA);

            // Double型
            DemoInfo<Double> cftD = new DemoInfo<Double>(23.56d);
            Double resD = cftD.getValue();
            System.out.println("Double型ジェネリクス: " + resD);

            // String型
            DemoInfo<String> cftB = new DemoInfo<String>("this is a test");
            String resC = cftB.getValue();
            System.out.println("String型ジェネリクス: " + resC);
      }

}

実行結果
Integer型ジェネリクス: 12345
Double型ジェネリクス: 23.56
String型ジェネリクス: this is a test

Java

Posted by arkgame