1

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?

3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

In addition, if you're performing any math then you'll want a primitive too
0

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

Comments