Integer.valueOf () value

Is there a reason to use Integer.valueOf (X) to initialize the final integer, as shown below:

public class MyClass
{
  public static final Integer DAY_1 = Integer.valueOf(1); // Why do it this way?
  public static final Integer DAY_2 = 2; // When it can be done this way?
}

I understand that this was necessary in older versions of Java before autoboxing was added. Is there a reason for this type of code? Or is it just a bad habit?

+3
source share
7 answers
  • There appeared a lot of code written before 1.5. There is no need to update it without any benefit.
  • In some cases, it’s clear that you are boxing. In the case when you gave you, you can easily see the type of target in one line - but this is not always the case.
  • , Integer int, Integer, .
+8

, , DAY_1 (), int.

, , , - .

+4

, (un) , . , , (Eclipse , ).

, , , .

+4

, ( ). , DAY_2, , DAY_1 .

. (un) , , , . , .

+1

, . - IDE /. , 1 .

, , .

.

+1

Integer.valueOf(1) ; -128 128 , , Integer (1) . , , (Integer, Long, BigDecimal ..), , , , autoboxing .

Bart van Heukelom, the difference between list.remove (1) and list.remove (new Integer (1)) is this; list.remove (1) will remove the object from index 1 from the list, list.remove (new Integer (1)) will remove all objects in the list that are equal to the Integer object with a value of one. Remember that collections cannot store primitives, only objects.

+1
source

This is a bad habit, and there is no reason for this, as the compiler will generate Integer.valueOf()for you.

-1
source

Source: https://habr.com/ru/post/1753355/


All Articles