简体   繁体   中英

HashSet Null Pointer Exception in Android but doesn't occur in java. why?

I was working with hashsets and somehow i came across NPE. I know hashset allow null values. So i tried to know what exactly happening and i created following code in java(just for learning purpose)

Java Code -

public class numbers {
static HashSet<String> s = new HashSet<>();

    public static void main(String[] args) {
        s.add("a");
        s.add(null);
        s.add("b");
        for(String l:s)
        {
            System.out.println(l);
        }
    }
}

It gave me no exceptions. The output is printed to the console. Then i tried to run the same code in android

Android Code -

public class MainActivity extends Activity {
    HashSet<String> s = new HashSet<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        s.add("a");
        s.add(null);
        s.add("b");

        for(String l:s)
        {
            //System.out.println(l);
            Log.i("ExceptionCheck", l);
        }
    }
}

Now when i run the application . Null pointer exception is raised at Log statement, where i am trying to read the output.

Can anyone explain me whats the difference ?

You have added a null to your set and then you're printing the values.

You cannot pass a null message to any of the Log print calls such as Log.i() . It will NPE with message "println needs a message" .

However, something like this works that ensures the message is not null:

Log.i("ExceptionCheck", "" + l);

That is because s.add(null); line

Console allow null values but Logcat doesn't

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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