Java – how to implement list, set and map in null free design?

In most cases, it's great when you can return null / empty objects to avoid null values, but what about collections like objects?

In Java, if the key in get (key) cannot be found in the map, the map returns null

In this case, I can think of the best way to avoid null values is to return an entry < T > object, which can be emptyentry < T >, or contain the value t

Of course, we avoid using null, but if you don't check whether it is emptyentry < T >, you can now have a class cast exception

Is there a better way to avoid null values in get (k) of map?

For argument, let's say that this language doesn't even have null, so don't say only use null

Solution

Two possible solutions

>Provide include (key) function If get (key) is called for a nonexistent key, an exception is thrown The drawback is to call get () after repeated operation of contains (). Inefficient. > Functional languages use may. In similar cases This article explains how to implement may in Java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>