【问题标题】:How to make an Integer instance not nullable [duplicate]如何使整数实例不可为空[重复]
【发布时间】:2014-07-30 22:01:27
【问题描述】:

有没有办法确保Integer 变量不是null

我需要创建一个整数值列表,所以我不能使用int 类型。我需要使用 List<Integer> 但这将允许 null 元素的值...

我是否需要使用List 的某些特定实现,或者有什么方法可以将Integer 设置为不可为空?

注意我需要List,而不是Set

【问题讨论】:

  • 您可以制作一个拒绝空值的包装器。
  • 你为什么不创建自己的 List 类来禁止拥有 null 值?
  • 编写自己的整数包装类
  • 显然,我们不想重新发明任何轮子。然而,并不是所有的轮子都被发明出来了(或者至少在你的情况下是公开实施的)。

标签: java list integer nullable


【解决方案1】:

你可以重写 List 的 add 方法并检查元素是否为 null。

new LinkedList<Integer>() {
    @Override
    public boolean add(Integer e) {
        if(e == null)
            return false;
        return super.add(e);
    }
};

您可能需要将此检查添加到其他插入方法中,例如 add(int pos, E value) 或 set(int pos, E value)。

【讨论】:

    【解决方案2】:

    只是为了完成上面的答案。如果您使用的是 java8,您可以从 Optional 类中受益。

    【讨论】:

      【解决方案3】:

      您可以在填充列表后尝试使用Google Guava Collections2.filter() 方法过滤掉空值:

          List<Integer> myList = new ArrayList<Integer>();
          myList.add(new Integer(2));
          myList.add(null);
          myList.add(new Integer(2));
          myList.add(new Integer(2));
          myList.add(null);
          myList.add(new Integer(2));
      
          myList = new ArrayList<Integer>(Collections2.filter(myList, new Predicate<Integer>() {
              @Override
              public boolean apply(Integer integer) {
                  return integer != null;
              }
          }));
      
          System.out.println(myList); //outputs [2, 2, 2, 2]
      

      【讨论】:

        【解决方案4】:

        使用队列实现,例如 LinkedBlockingQueue,其中许多不允许空值。

        http://docs.oracle.com/javase/tutorial/collections/implementations/queue.html

        我也推荐你看看 Lombok 的 NonNull 注解:

        http://projectlombok.org/features/NonNull.html

        【讨论】:

          【解决方案5】:

          不,没有。最简单的方法就是添加一个预检查:

          if (intVal != null) {
            list.add(intVal);
          } else {
           // TODO: error handling
          }
          

          无论如何,您都必须为您的自定义数据结构处理异常/返回值,这不允许 NULL。

          【讨论】:

            猜你喜欢
            • 2020-06-19
            • 1970-01-01
            • 1970-01-01
            • 2022-01-24
            • 2021-04-25
            • 1970-01-01
            • 2022-01-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多