← Back to context

Comment by JanisErdmanis

3 days ago

> if you wanted to store an integer in a collection, you had to manually convert to and from the primitive int type and the Integer “boxed” class

I have never worked with Java. What is this? Why would one want to have a class for an Integer?

Primitive variables in Java, such as `int`, `boolean`, and `double`, store their actual values directly in memory. When they are local variables inside a method, this memory is typically allocated on the thread's stack. These primitives do not have the structure or overhead of an object, including the object header used by the Garbage Collector (GC) to manage heap-allocated objects.

If a primitive value must be treated as an object (e.g., when stored in a Java Collection like ArrayList or when passed to a method that requires an object), Java uses a process called `boxing` to wrap the primitive value into an instance of its corresponding Wrapper class (e.g., Integer, Boolean, Double). These Wrapper objects are allocated on the heap and do possess the necessary object header, making them subject to the GC's management.

  • Aside from this, having such a class provides a convenient place to hold all the int utility functions, and the same for the other primitive types.

It's because the collection types (and generics) don't support primitives, only objects. So you been to stuff the primitives into objects to use them with a lot of the standard library.

  • One of the more amusing bugs I had to figure out resulted from the fact that some of the autoboxed values get cached, resulting in peculiar behaviour when someone managed to reflectively change the boxed primitive value...

    i.e. something like:

      Integer x = 42
      highlyQuestionableCode(x);
      println(x); // "24" WAT?
    

    I'm a fan of JEP-500...

    https://openjdk.org/jeps/500

  • That doesn't sound very pleasant.

    • Well, it was annoying until autoboxing came in.

        // Before autoboxing
        list.add(new Integer(42));
      
        // After autoboxing
        list.add(42);
      

      Mostly it's a non-issue now. If you're desperately cycle/memory constrained you're likely not using Java anyway.

      5 replies →

    • There are libraries, like fastutil, that provide collections for primitive types.

    • Either the same of this feature or always hiding the boxing (e.g. a Python int is actually a wrapper object as well, with some optimizations for some cases like interning) is the case in almost all languages.

      1 reply →

I think your intuition is correct: you probably don’t.

That’s also very likely changing. Lookup “project Valhalla”. It’s still a work in progress but the high level goal is to have immutable values that “code like a class, work like an int”.

PS When I say “changing”: it’s being added. Java tries hard to maintain backward compatibility for most things (which is great).