K
K
kidar22015-03-10 10:24:19
Java
kidar2, 2015-03-10 10:24:19

If (value == null || value.equals(null)))?

I saw such a strange condition in someone else's code:

static String valueToString(Object value) throws JSONException {
        if (value == null || value.equals(null)) {
            return "null";
        }
}

How can the second condition work without the first one?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor Gogilchin, 2015-03-10
@lslayer

For a particular object, the equals() method can be overridden.
For example, according to business logic tasks, an object is considered null if its "MostMainField" is null.
In this case, it's either an old uncorrected code (before, it was not Object that came as a parameter, but something else) or a banal error.
In general, in the case of a custom class, the second condition without the first one can work.
For example:

package tk.lslayer.temp;

public class NullComparator {
    public Integer someField = null;

    @Override
    public boolean equals(Object obj) {
        if (obj == null && someField == null) return true;
        if (obj != null && obj instanceof NullComparator) {
            return ((NullComparator) obj).someField == someField ? 
                true : false;
        } else return false;
    }

    public static void main(String[] args) {
        NullComparator comparator1 = new NullComparator();
        
        if (comparator1 == null)
            System.out.println("!= null");
        if (comparator1.equals(null)) 
            System.out.println(".equals(null)");
    }
}

M
Moxa, 2015-03-10
@Moxa

I think that there is special magic for json processing.. suppose that value is some JsonItem that stores a value, this value can be null, for this the second check is made

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question