|
Re: Strange warning: Potential null pointer access [message #782666 is a reply to message #782632] |
Tue, 24 January 2012 07:21 |
Ed Merks Messages: 33140 Registered: July 2009 |
Senior Member |
|
|
Eugene,
Comments below.
On 24/01/2012 5:54 AM, Eugene wrote:
> Eclipse IDE for Java EE Developers 1.4.1.20110909-1818
> Eclipse Platform 3.7.1.M20110909-1335
>
> Potential null pointer access: The variable l may be null at this
> location
>
> public class TestPotentialNullPointer
> {
> public void test()
> {
> List<String> l = getList();
> int size = l != null ? l.size() : 0;
>
> >> for (String s : l) { <<
The computation for size indicates that you expect s might be null
earlier so it might be null here too.
>
> System.out.println(s);
> }
> }
>
> private List<String> getList()
> {
> List<String> l = new ArrayList<String>();
> return l;
> }
> }
>
> but
>
> public class TestPotentialNullPointer
> {
> public void test()
> {
> List<String> l = getList();
>
> for (String s : l) {
> System.out.println(s);
> }
> }
>
> private List<String> getList()
> {
> List<String> l = new ArrayList<String>();
> return l;
> }
> }
>
> no warnings
Worse is that even if you did
for (int i = 0; i < size; i++)
{
System.out.println(l.get(i));
}
you'd still get a warning, even though it's not possible for l to be
null if size > 0. I.e., the compiler isn't smart enough to do this
indirect analysis that you've properly guarded against null...
Ed Merks
Professional Support: https://www.macromodeling.com/
|
|
|
Powered by
FUDForum. Page generated in 0.02347 seconds