0

I'm making a class that uses an ArrayList as a data member. I want everything to be consistent in the class; so, I used Integer instead of int in the entire class and in everywhere.

For example these functions:

public Integer getMax();
public void sort(Integer n);

My question: is this better than using int? Can someone define the following: ?

int i = obj.getMax();

// or this:
int size = 0;
obj.sort(size);

I know that Integer is an object type whereas int is a primitive type. However, I don't really know the difference in usage in such cases!

When is it better to use Integer and when is it better to use int?

  • Possible duplicate of: [http://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-java-and-c](http://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-java-and-c) – Aycan Yaşıt Dec 26 '14 at 13:28
  • In terms of implementing `max` and `sort` I suggest you look at how this is done in Java 8. `max` returns an Optional which is considered better practice than returning `null` – Peter Lawrey Dec 26 '14 at 13:33
  • @AycanYaşıt, no it's not duplicate! –  Dec 26 '14 at 13:34

3 Answers3

2

Integer is a wrapper class over primitive int. AutoBoxing and Unboxing convert int to Integer and Integer to int respectively. So,

    Integer i = 5;         // Autoboxing
    int val = new Integer(15); // Unboxing

are valid statements So, wherever possible use primitive int. if you need to use Collections use Integer. Why??. Because, Objects have overhead during creation and usage.

TheLostMind
  • 34,842
  • 11
  • 64
  • 97
1

In your case:

If you return an Integer in the getMax(); you are telling the caller that he can expect null to be returned. With 'int' you don't have this problem.

Apart from that, Integer wrapper object can be more expensive due to gc litter and JIT having a more difficult time to optimise.

So use int when you can, Integer when there is no other option.

pveentjer
  • 7,395
  • 3
  • 18
  • 31
0

As simple as, when ever I need to deal with Object's I go for Integer (for ex: Collections), otherwise I prefer primitive.

Suresh Atta
  • 114,879
  • 36
  • 179
  • 284