Java 如何避免在 ArrayList 中插入空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21600559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:36:29  来源:igfitidea点击:

How to avoid null insertion in ArrayList?

java

提问by Ramesh Basantara

How to avoid null insertion in ArrayList while inserting element?

插入元素时如何避免在ArrayList中插入空值?

ArrayList<String> al=new ArrayList<String>();
al.add(null);//should avoid
.
.
.
al.add("Ramesh");

回答by Mikescher

You could create your own ArrayList-Class (derived from the original) and override the Add-Method
Then you could check for null when Adding.

您可以创建自己的 ArrayList-Class(派生自原始)并覆盖 Add-Method
然后您可以在添加时检查 null。

@Override
public boolean add(E e) {
  if (e == null) return false;
  else return super.add(e)
}

As Mark stated in the comments you perhaps want to override all other possibilties of Adding values too. (see the doc)

正如马克在评论中所述,您可能也想覆盖添加值的所有其他可能性。(见文档

  • add(E e)
  • add(int index, E element)
  • addAll(Collection c)
  • addAll(int index, Collection c)
  • set(int index, E element)
  • 添加(E e)
  • 添加(整数索引,E 元素)
  • addAll(集合 c)
  • addAll(int 索引,集合 c)
  • 设置(整数索引,E 元素)

回答by Maroun

Avoiding nullcan be harmful sometimes and it could hide possible bugs.

避免null有时可能是有害的,它可能会隐藏可能的错误。

If you're worried about getting NullPointerExceptionin some stage, you can simply check if the item stored in the ArrayListis null.

如果您担心进入NullPointerException某个阶段,您可以简单地检查存储在ArrayListis 中的项目null

You cannot disallow inserting nullto ArrayList.

您不能禁止插入nullArrayList.

回答by Ruchira Gayan Ranaweera

You can try something like that, But if you want to do exactly what you are trying you have to rewrite add()in ArrayListclass. Using this validation you can avoid null

您可以尝试类似的方法,但是如果您想完全按照您正在尝试的方式进行操作,则必须add()ArrayList课堂上重写。使用此验证,您可以避免null

public static void main(String[] args) {
    ArrayList<String> al=new ArrayList<String>();
    al=add(al,null);
    al=add(al,"Ramesh");
    al=add(al,"hi");
}

public static ArrayList<String> add(ArrayList<String> al,String str){
   if(str!=null){
      al.add(str);
      return al;
   }else {
      return al;
   }
}

In this case you have to call your custom addmethod to add element

在这种情况下,您必须调用自定义add方法来添加元素

回答by stan

ArrayList<String> al = new ArrayList<String>() {

            @Override
            public boolean add(String s ) {

                if( s != null ) {
                    return super.add( s );
                }
                return false;
            }
        };
al.add(null);
al.add("blabla");