これはあまり知られていませんが、Sun の javac コンパイラ API には、append()
や などのメソッドを使用して新しい不変リストを返す不変リストの実装が含まれていますprepend()
。それを使用するtools.jar
には、クラスパスと次の import ステートメントが必要です。
import com.sun.tools.javac.util.List;
サンプルコード:
final List<Integer> list = List.of(6, 7);
System.out.println(list);
final List<Integer> newList =
list.prepend(5) // this is a new List
.prependList(List.of(1, 2, 3, 4)) // and another new List
.append(8) // and another
.reverse(); // and yet another
System.out.println(newList);
System.out.println(list == newList);
System.out.println(list.getClass());
System.out.println(newList.getClass());
出力:
6,7
8,7,6,5,4,3,2,1
false
クラス com.sun.tools.javac.util.List
クラス com.sun.tools.javac.util.List
これは内部 API であり、本番環境では使用しないでください。
注:Collection
およびList
インターフェース ( など)のすべての標準の変更可能なメソッドは、明らかにadd()
addAll()
throwです。UnsupportedOperationException
参照: