-1
import java.util.ArrayList;
import java.lang.Math;
class Main {
  public static void main(String[] args) {
    ArrayList list = new ArrayList();
    list.add((int) (Math.random() * 100 + 1));
    list.add((int) (Math.random() * 100 + 1));
    list.add((int) (Math.random() * 100 + 1));
    System.out.print (list);
  }
}

Just wondering why this works? It is my understaning that ArrayLists are not supposed to accept primitives like integers but yet this clearly works and does not display any errors?

DIowa
  • 9
  • 1

1 Answers1

1

The explanation is that int values are being autoboxed into Integer objects due to autoboxing. This was already addressed in comments, but here is a relevant snip from the Java Language Spec about autoboxing:

At run time, boxing conversion proceeds as follows:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

Also this:

Ideally, boxing a primitive value would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rule above is a pragmatic compromise, requiring that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, the rule disallows any assumptions about the identity of the boxed values on the programmer's part. This allows (but does not require) sharing of some or all of these references. Notice that integer literals of type long are allowed, but not required, to be shared.

Community
  • 1
  • 1
Kaan
  • 5,434
  • 3
  • 19
  • 41