具有空指针异常的Java流

时间:2019-02-11 18:31:15

标签: java nullpointerexception

我在Java流api中面临空指针异常

  

我的模型班:

public class Member
    {
     String name;
     String age;
     String gender;

     public String getName() {
        return name;
     }

     public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
    }
  

ModelList类:

import java.util.List;

   public class MemberList {
   List<Member> member;
   int count;
    public List<Member> getMember() {
        return member;
    }

    public void setMember(List<Member> member) {
        this.member = member;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
    }
  

Main.java

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main( String[] args ) {

        MemberList list = new MemberList( );
        List< Member > memberList = new ArrayList<>( );
        for ( int i = 0; i < 10; i++ ) {
            Member member = new Member( );
            member.setAge( 10 + "" );
            member.setName( null );
            member.setGender( null );
            memberList.add( member );
        }
        Member member = null;
        memberList.add( member );
        Member m = new Member( );
        m.setGender( "MALE" );
        list.setMember( memberList );
        list.setCount( 10 );
        list.getMember( )
            .stream( )
            .filter( obj -> Objects.nonNull( obj ) )
            .filter( obj -> Objects.nonNull( obj.getGender( ) ) )
            .filter( obj -> obj.getGender( )
                               .equals( "MALE" ) )
            .collect( Collectors.toList( ) );
    }
}

我知道Member list对象是否为null意味着流给出了空指针异常,并且getGender等于null意味着java流给出了空指针异常。现在我的问题是如何在Java中处理这种空指针异常

2 个答案:

答案 0 :(得分:0)

NullPointerException可以通过从根本上消除null值到对象中而消除。

您担心list.getMember()可能会返回null吗?
采取一些预防措施。

// Use annotations to mark that this method doesn't accept null
// Check for a possible null value

@NotNull
public List<Member> getMember() {
    return Collections.unmodifiableList(member);
}

public void setMember(@NotNull final List<Member> member) {
    this.member = member != null 
           ? new ArrayList(member)
           : Collections.emptyList();
}

答案 1 :(得分:0)

您的成员列表包含一个null成员实例,然后您将此列表影响到变量列表,因此,您的列表包含一个数字,该数字引用了null指针 抱歉我的英语我是初学者