繁体   English   中英

Java 是否有 Null 的包装类型?

[英]Does Java have a wrapper type for Null?

我需要区分具有 null 值的属性和根本不存在的属性。 我可以使用 map,但出于性能原因,我尝试使用固定大小的数组。

在数组中,我可以使用null来指示属性何时根本不存在。 但是,对于确实存在并且 null 值的属性,是否有标准方法可以在数组中表示它?

我想保留一个 static 成员,例如

class MyClass {

    private static final Object NULL = new Object();   // null wrapper
    
    private Object[] m_arr = new Object[10];

    // 'i' represents the index of a property in the array

    boolean exists(int i) {
        return m_arr[i] != null;
    }

    Object value(int i) {
        if( !exists(i) ) throw new NullPointerException();   // does not exist
        if( m_arr[i] == NULL ) return null;

        // ... handling for other data types ...
    }
}

代表 null 的另一种可能性可能是枚举?

class MyClass {
      ...
      enum Holder {
            NULL
      }
      ...
      // to check for a null value use m_arr[i] == Holder.NULL
}

使用可选的,例如

private Optional<String> myField;

有三种状态。 以下是如何处理它们:

myfield = Optional.of("foo"); // attribute has non-null value
myfield = Optional.empty();   // attribute is present, but null
myfield = null;               // attribute is not present

Jackson (ie Spring boot) json deserialization supports this out of the box, which is very handy for handling PATCH methods that require the distinction between a json key being specified but null and not specified.

不...但是,Java 现在有Optional可以视为相同。 您还可以创建一个 class 来表示一个 null object,这可以按照“Null Z497031794414A53B544BAC”完成。 我在博客中写过这个: https://www.professorfontanez.com/2020/04/the-beauty-of-null-object-pattern.html

Apache commons ObjectUtils有一个NULL字段用于此目的,如果您不想定义自己的。

Java 是否有 Null 的包装类型?

不。

但是我如何解决这个问题意味着您不需要包装器:只需维护一组代表“显式” null 值的索引。

class MyClass {
    private Object[] m_arr = new Object[10];
    private Set<Integer> presentButNullIndices = new HashSet<>();

    // 'i' represents the index of a property in the array

    Object value(int i) {
        if (m_arr[i] == null && !presentButNullIndices.contains(i)) {
            throw new NullPointerException();
        }
        // ... handling for other data types ...
    }

    // just an example of how to maintain the set
    void insert(int i, Object value) {
        if (value == null) {
             presentButNullIndices.add(i);
        }
        else {
             presentButNullIndices.remove(i);
        }
        m_arr[i] = value;
    }
}

最坏的情况,空间复杂度翻倍,但这仅适用于大量使用 null 值的客户端。 contains在一个集合上是 O(1)

我还考虑首先禁止 null 值。 一些 map 实现可以做到这一点,我从来没有发现自己处于我希望他们不这样做的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM