Java21 Collection 的 getFirst

meow meow meow meowwwww....
最近習慣了讓 github 的 copilot 來 review 協助, 其中一個提示是 getFirst 的風險.
If cmd.getPolicies() returns a standard List, using getFirst() might cause runtime issues. Consider using get(0) to retrieve the first element or ensure the list supports getFirst().
getFirst 為何會產生 runtime issue
首先 getFirst() 是 List 介面繼承自 SequencedCollection 才有的方法, 而 SequencedCollection 是 java21 才有支援的. 因此若由 java21 compiler 產生 byte code 然後跑在 java21 以下的版本, 可能會產生 runtime 的錯誤與風險. 因此建議的寫法是改用 get(0) 來取得第一個元素.
intelliJ 的警告
當我改寫回 get(0) 我的 IDE (intelliJ) 警示我應該改寫回 getFirst(), 這有許多做法
忽略 intelliJ 的警告, 比如說加上
@SuppressWarnings但這有風險. 原因在於@SuppressWarnings作用的範圍是 class, method, args 的層級, 因此在我的情境可能需要添加在 method 層級, 這會導致 compiler 忽略其他錯誤.用 stream 改寫
myCollections.stream().findFirst().orElaseThrow(…), 轉為 stream 再處理 first Element.用三元判斷改寫
var element = myCollections.isEmpty() ? null : list.get(0);
我的取捨
在我控制的部署策略並不存在於 java21 compiler 跑在 java21 以下的版本, 目前也不打算支援, 所以
getFirst()的改寫需求並不存在, 可以忽略 code review 建議.若
myCollections絕對不會發生 null 或是 empty 的情況, 我會使用三元判斷式, 這取決於建立 Stream 會產生額外的記憶體成本, 且並沒有完全運用到 stream 的其他諸如filter()運算, 感覺上有點殺雞用牛刀的感覺.非 List 的操作, 我認為有需要使用 stream 的處理, 因為
Set,Collection沒有順序保證, 難保證getFirst()的結果.



