0

Java has a class called Integer that is commonly used to wrap the primitive type int when declaring data structures, etc. When using this class to wrap int you can (as far as I understand) treat the elements you get from the data structure as type int.

For example, if I have the following code it would run properly

// size of ArrayList
int n = 5;

//declaring ArrayList with initial size n
ArrayList<Integer> arrli = new ArrayList<Integer>(n);

//Appending the new element at the end of the list
    for (int i=0; i<n; i++)
        arrli.add(i);

int result = arrli.get(1) + arrli.get(2);

and result would have the value 3 as expected.

My question is how is this actually implemented under the hood? Java has no mechanism for overriding operators, etc so how does Java cleverly know how to treat the class Integer in this way?

samuelnj
  • 1,577
  • 7
  • 18
  • 1
    This should be sufficient to understand how it works: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html. If you need a deeper understanding, the linguistic "mechanisms" are described in detail in the Java Language Specification. – Stephen C May 20 '18 at 04:45
  • The mechanism is called **auto** boxing. You are not adding up Integer objects. The compiler secretly inserts the required code to turn Integer objects into int values, and these get added. – GhostCat May 20 '18 at 05:01

0 Answers0