不返回 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'stopfeatureSnificallyEnhanceItsperFormanCeanDscalability.1)对象 - 方向 - incipleslike-polymormormormormormormormormormormormormorableablefleandibleandscalablecode.2)garbageCollectionAutoctionAutoctionAutoctionAutoctionAutoctionautomorymanatesmemorymanateMmanateMmanateMmanagementButCancausElatenceiss.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)对象 - 方向 - 方向上的贝利奥洛夫夫人 - 启动worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定建筑,影响性能,安全性和便携性。1)theclassloaderloader,links andinitializesClasses.2)executionEccutionEngineExecutionEngineExecutionEngineExecuteByteCuteByteCuteByteCuteBytecuteBytecuteByteCuteByteCuteByteCuteBytecuteByteCodeNinstRonctientions.3)Memo.3)Memo


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。