Java - Which is best to use in firestore int or Integer?

Viewed 347

Hi and please help me again. I have this like in docs:

cities
 \
  - id_number
        \
         - "population": 860000
        \
         - "name": San Francisco

And I have POJO class.

One:

public class City {
    public String name;
    public int population;  ** int **

    public City() {}
}

Two:

public class City {
    public String name;
    public Integer population; ** Integer **

    public City() {}
}

Which is best to use int or Integer in my POJO class?

2 Answers

Wrapper classes are objects encapsulating primitive Java types. So even if you are using the primitive int or the object version, which in this case is the Integer class, will map to the exact same type in the Cloud Firestore database. See here Firestore supported data types.

Which is best to use int or Integer in POJO?

There is no best option, it is entirely up to you to decide which of these options are you more comfortable with. I'm using for my model classes the primitive types because if you are using the object versions, there might be cases in which the values might be null at some point.

So, int is a primitive, and Integer is a boxed primitive (also boxed type).

In general:

Prefer using primitives over boxed types.

Use Boxed types when:

  1. Using parameterized types (list Collection). Parameterized types do not permit primitives.
  2. Using value as a key or value in Collections.
  3. Using reflective method invocation (another don't do). e.g. class.forName("java.lang.Integer");

Source: Effective Java by Joshua Bloch.

In your case:

If population is missing in database, should it be initialized to 0 (in case of primitives) or to null(in case of boxed types)? In my opinion, 0 means something. It means that there are 0 citizens, nobody lives there. Also, you will have to do the check population > 0 to see if the value is present. Despite of the general recommendation, in this case I would go for boxed Integer type.

Related