List 与 null 的故事

把 null 加到 list里会怎么样?

        List<String> list = new ArrayList<String>();
        list.add(null);
        list.add(null);

        print(list.size());  //将打印:2

        list.remove(null);
        print(list.size());  //将打印:1

随贴附送“清除null”的java方法

    static <T> List<T> getNonNullElements(List<T> list){
        List<T> resultList = new ArrayList<T>();
        for(T t: list){
            if(t != null){
                resultList.add(t);
            }
        }
        return resultList;
    }

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.