Reputation: 3362
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 ?
Upvotes: 1
Views: 333
Reputation: 152867
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);
Upvotes: 5
Reputation: 14590
That is because s.add(null);
line
Console
allow null
values but Logcat doesn't
Upvotes: 4