不回傳 null:
- 傳回 null 代替空集合或陣列的方法需要額外的客戶端處理以避免異常。
null 問題:
- 客戶端需要新增冗餘檢查(如果要檢查 null)。
- 這些檢查中的遺漏可能會被忽視,從而導致錯誤。
- 這使得傳回集合或陣列的方法很難實現。
反對 null 的論證:
- 不要擔心分配空集合或陣列的效能,除非它被證明是瓶頸。
高效替代方案:
- 使用空集合或陣列而不是 null。
- 不可變集合可以重複回傳(例如:Collections.emptyList()、Collections.emptySet())。
- 空數組也可以高效率回傳。
最佳化效能:
- 使用可重複使用的空不可變集合來避免不必要的新分配。
- 傳回相同的空數組,而不是每次建立一個新數組
程式碼範例:
傳回 null 的錯誤方法:
// Exemplo incorreto public List<cheese> getCheeses() { return cheesesInStock.isEmpty() ? null : new ArrayList(cheesesInStock); } </cheese>
客戶待遇不足:
List<cheese> cheeses = shop.getCheeses(); if (cheeses != null && !cheeses.isEmpty()) { // Lógica para lidar com queijos disponíveis } </cheese>
傳回空集合的正確方法:
// Exemplo correto public List<cheese> getCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList(cheesesInStock); } </cheese>
使用不可變的空集合:
public List<cheese> getCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList(cheesesInStock); } </cheese>
與空數組一起使用:
// Retorno de array vazio corretamente public Cheese[] getCheeses() { return cheesesInStock.toArray(new Cheese[0]); }
最佳化空數組的使用:
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0]; public Cheese[] getCheeses() { return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY); }
結論:
永遠不要傳回 null:總是更喜歡空集合或陣列。這簡化了 API,防止錯誤,並且很少對效能產生負面影響。
以上是Item - 傳回空集合或陣列而不是 null的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

java'stopfeatureSnificallyenhanceItsperformanCandScalability.1)對象 - 方向clincipleslike-polymormormormormormormormormormormormorableableflexibleandscalablecode.2)garbageCollectionAutectionAutoctionAutoctionAutoctionAutoctionAutoctionAutoMenateMememorymanateMmanateMmanateMmanagementButCancausElatemention.3)

JVM的核心組件包括ClassLoader、RuntimeDataArea和ExecutionEngine。 1)ClassLoader負責加載、鏈接和初始化類和接口。 2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。 3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector組成,負責bytecode的執行和優化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)對象 - 方向 - 方向上的allowslowsmodelowsmodelingreal-worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定結構,影響性能,安全性和便攜性。 1)theclassloaderloader,links andinitializesClasses.2)theexecutionEngineExecutionEngineExecutionEngineExecuteNexeCuteByteCuteByteCuteByTecuteByteCuteByteCuteBytecuteBytecuteByteCoDeinintolachineinstructionsions.3)Memo.3)Memo


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1
好用且免費的程式碼編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載
最受歡迎的的開源編輯器