バックエンドのAPI実装で空のListを返したいことがあり調べたのでメモ。 知っていたのは新しいインスタンスを生成してreturnする。 他に便利な方法がないかと思ったらちゃんとあった。 なおソースコードはもともとListを返すメソッドがあり、条件に一致したら空のListを返す、のような使い方を想定しているため少し冗長。
これが知っていた方法。 新しくインスタンスを生成してそのまま返してあげれば空のListになる。
public class Main {
public static void main(String[] args) {
List<String> emptyList = generateEmptyList();
System.out.println(emptyList);
}
/**
* 空のListを生成する
*
* @return 空のList
*/
public static List<String> generateEmptyList() {
return new ArrayList<>();
}
}
Collectionsの中にそのまんまのメソッドがあった。 新しいインスタンスを生成することなく空のListを作れる。 ただし変更ができない(immutable)Listなのは注意が必要。
public class Main {
public static void main(String[] args) {
List<String> emptyList = generateEmptyList();
System.out.println(emptyList);
}
/**
* 空のListを生成する
*
* @return 空のList
*/
public static List<String> generateEmptyList() {
return Collections.emptyList();
}
}
emptyList()
の実装を見ると EMPTY_LIST
という定数を返しているだけだった。
なのでこうも書ける。
/**
* 空のListを生成する
*
* @return 空のList
*/
public static List<String> generateEmptyList() {
return Collections.EMPTY_LIST;
}
Java9以上であれば List.of()
が使える。
これもimmutableなList。
public class Main {
public static void main(String[] args) {
List<String> emptyList = generateEmptyList();
System.out.println(emptyList);
}
/**
* 空のListを生成する
*
* @return 空のList
*/
public static List<String> generateEmptyList() {
return List.of();
}
}