如何在无空设计中实现 List、Set 和 Map? [英] How to implement List, Set, and Map in null free design?

查看:23
本文介绍了如何在无空设计中实现 List、Set 和 Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数情况下,您可以返回一个空/空对象以避免空值,这很好,但是像对象这样的 Collection 呢?

Its great when you can return a null/empty object in most cases to avoid nulls, but what about Collection like objects?

在Java中,如果get(key)中的key在地图中没有找到,Map返回null.

In Java, Map returns null if key in get(key) is not found in the map.

我能想到的在这种情况下避免 null 的最好方法是返回一个 Entry 对象,它是 EmptyEntry<;T>,或包含值 T.

The best way I can think of to avoid nulls in this situation is to return an Entry<T> object, which is either the EmptyEntry<T>, or contains the value T.

当然我们避免了 null,但是现在如果您不检查它是否为 EmptyEntry,您可能会遇到类转换异常.

Sure we avoid the null, but now you can have a class cast exception if you don't check if its an EmptyEntry<T>.

是否有更好的方法来避免 Mapget(K) 中的 null?

Is there a better way to avoid nulls in Map's get(K)?

为了论证起见,假设这种语言甚至没有 null,所以不要说只使用 nulls.

And for argument sake, let's say this language don't even have null, so don't say just use nulls.

推荐答案

两种可能的解决方案:

  1. 提供一个 contains(key) 函数.如果为不存在的键调用 get(key) 则抛出异常.缺点是:在contains()重复操作后调用get();效率不高.

  1. Provide a contains(key) function. Throw an exception if get(key) is called for a non-existent key. The downside is: calling get() after contains() duplicates operations; not efficient.

函数式语言在类似的情况下使用 Maybe.这篇文章解释了如何在Java中实现Maybe.

Functional languages use Maybe in similar situations. This article explains how to implement Maybe in Java.

这篇关于如何在无空设计中实现 List、Set 和 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆