0

I'm newbe in Java and I've got some questions about using constructors. In what situations I should use new Integer() statement? Look at the code:

    Integer a = 129;//1
    Integer b = new Integer(129);//2
    List<Integer> list= new ArrayList<Integer>();
    list.add(new Integer(1));//3
    list.add(2);//4

Which row is the example of bad programming practise?

Tony
  • 3,605
  • 14
  • 52
  • 84

2 Answers2

3

Using new Integer() will guarantee that you have a new Integer object reference.

Using the value directly will not guarantee that, since auto boxing int to Integer may not do that object instantiation.

I would say that you will only need new Integer(1) in really strange edge cases, so most of the time I would say you never need to do new Integer...

Also please bear in mind that auto boxing / unboxing may produce some errors in some edge cases.

Integer x = null;
int y = x; // Null Pointer Exception

Long iterations where auto(un)boxing is happening may have a performance cost that an untrained eye might not notice

Tiago
  • 934
  • 6
  • 15
2

Use autoboxing as a default pattern - it's been about forever and makes life ever-so-slightly easier.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, ..

While there are slight difference with new Integer (see other answers/comments/links), I generally do not consider using new Integer a good approach and strictly avoid it.

user2246674
  • 7,621
  • 25
  • 28