I have never worked with Java. What is this? Why would one want to have a class for an Integer?
I have never worked with Java. What is this? Why would one want to have a class for an Integer?
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.
Java uses Type Erasure for Generics, which means that generic type variables are checked at compile time, but that type information is not available at runtime. At compile time you may have List<Foo> and List <Bar> but at runtime its all just List<Object> (Object being the base type everything inherits from). Basically List stores a bunch of pointers to objects and since pointers can point to anything a List can basically "store" anything.
Then you have a divide between primitives and Objects in Java, where primitives are double, int, boolean etc.. Primitives are types in the C-sense, e.g. int is nothing more than a 32-bit number, not a class in the Java-sense. But since ints are not classes and as such do not inherit from Object, they cannot be placed inside of List<Object>. Therefore there cannot be a List<int>. But there is Integer, which is an Object-wrapper around an int, meaning you can have a List<Integer>. This is called boxing and like all indirection carries a performance penalty.
Java hopes to heal this rift between primitives and Objects through something called Project Valhalla which has been 10 years in the making and is expected to land in the next two years or so.
Hope this ramble is comprehensible.
// 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.Edit: actually, if someone here is using it for something like that I'd love to hear the rationale...?
It's mostly a trade-off. Java's tooling, reliability and ecosystem is some of the best around. Even though building high performance software in Java is a bit of a pain, looking at the bigger picture, it's often still worth it.
Java Cards would like to have a word with you. But yeah I know what you mean.
i.e. something like:
Integer x = 42
highlyQuestionableCode(x);
println(x); // "24" WAT?
I'm a fan of JEP-500...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).