「Java」ジェネリックメソッドの定義のサンプル
書式
1.ジェネリックメソッドの定義
public static <T>ArrayList<T>メソット名(T t){//some code}
2.ジェネリックメソッドを呼び出す
ArrayList<クラス名> psLst = getFunc(オブジェクト変数名);
使用例
1.ジェネリックメソッドを定義
package com.arkgame.demo;
import java.util.ArrayList;
public class SamTestDemo {
public static void main(String[] args) {
// Personのオブジェクトの定義
Person ps = new Person();
ps.setAge(33);
ps.setUsername("adminuser");
// ジェネリックス型はクラスのオブジェクト
ArrayList<Person> psLst = getFunc(ps);
for (Person psn : psLst) {
System.out.println("年齢: " + psn.getAge());
System.out.println("ユーザ名: " + psn.getUsername());
}
}
// ジェネリックスメソッドの定義 戻り値の型がArrayList<T>
public static <T> ArrayList<T> getFunc(T t) {
ArrayList<T> cftLst = new ArrayList<T>();
cftLst.add(t);
return cftLst;
}
}
package com.arkgame.demo;
import java.util.ArrayList;
public class SamTestDemo {
public static void main(String[] args) {
// Personのオブジェクトの定義
Person ps = new Person();
ps.setAge(33);
ps.setUsername("adminuser");
// ジェネリックス型はクラスのオブジェクト
ArrayList<Person> psLst = getFunc(ps);
for (Person psn : psLst) {
System.out.println("年齢: " + psn.getAge());
System.out.println("ユーザ名: " + psn.getUsername());
}
}
// ジェネリックスメソッドの定義 戻り値の型がArrayList<T>
public static <T> ArrayList<T> getFunc(T t) {
ArrayList<T> cftLst = new ArrayList<T>();
cftLst.add(t);
return cftLst;
}
}
package com.arkgame.demo; import java.util.ArrayList; public class SamTestDemo { public static void main(String[] args) { // Personのオブジェクトの定義 Person ps = new Person(); ps.setAge(33); ps.setUsername("adminuser"); // ジェネリックス型はクラスのオブジェクト ArrayList<Person> psLst = getFunc(ps); for (Person psn : psLst) { System.out.println("年齢: " + psn.getAge()); System.out.println("ユーザ名: " + psn.getUsername()); } } // ジェネリックスメソッドの定義 戻り値の型がArrayList<T> public static <T> ArrayList<T> getFunc(T t) { ArrayList<T> cftLst = new ArrayList<T>(); cftLst.add(t); return cftLst; } }
2.Personクラスの定義
public class Person {
private String username;
private int age;
//get setメソッドの省略
}
public class Person {
private String username;
private int age;
//get setメソッドの省略
}
public class Person { private String username; private int age; //get setメソッドの省略 }
結果
年齢: 33
ユーザ名: adminuser