What are the wrappers variables for?

1

In what kind of circumstances can you apply?

Example:

// Inicializar Primitivos 
int  i1 = 12; 
    int  i2 = 300;
long l1 = 200L; // sufijo para primitivo long
long l2 = 200l; // sufijo para primitivo long
long l3 = 200;
float f1 = 1e-39F; // sufijo para primitivo float
float f2 = 1e+11f; // sufijo para primitivo float
float f3 = 1;
double d1 = 32e46d; // sufijo para primitivo double
double d2 = 14D; // sufijo para primitivo double
double d3 = 1; 

// Inicializar "Wrappers" con primitivos
Integer wi1 = new Integer(i1);
Long wl1 = new Long(l1);
Float wf1 = new Float(f1);
Double wd1 = new Double(d1);

and why?

Thanks!

    
asked by Antonio Alejos 18.10.2018 в 18:17
source

1 answer

4

Mainly there are two reasons:

  • Primitive types are not objects, so

    • do not extend Object :

      private output( Object o) { ...} //admite cualquier cosa menos un tipo primitivo
      
    • can not be used with generics:

      List<Integer> lista= ... //válido
      List<int> lista= ... //error
      
  • Sometimes you may want to want your model in Java to be nullable : When saving values in databases, saving 0 is not the same as saving null .

That said, since Java 5 (2004?) the language supports boxing / unboxing :

 Integer i = 5; //los tipos primitivos se transforman en objetos automáticamente

 listaInteger.add(50); //compila perfectamente
 int num = listaInteger.get(0); //cuidado con los NPE!
    
answered by 18.10.2018 / 18:36
source