Sub topic 3
Overload Resolution, Collections, and Boxing Costs
Assume you know Java primitive types, classes, ==, equals, and basic generic collections. Java chooses an overloaded method in phases:
- Fixed-arity methods without boxing, including primitive widening.
- Fixed-arity methods that allow boxing or unboxing.
- Variable-arity methods using varargs.
Because widening is considered before boxing, an overload may not be selected as you expect.
Widening before boxing
public class OverloadExample {
static void show(long value) {
System.out.println("long");
}
static void show(Integer value) {
System.out.println("Integer");
}
static void show(String... values) {
System.out.println("varargs");
}
public static void main(String[] args) {
show(5); // long: int widens to long
show(Integer.valueOf(5)); // Integer: exact reference match
show(); // varargs
}
}Java does not box 5 into Integer when 5 can first widen to long. Varargs is considered only after fixed-arity choices fail.
Wrappers in collections and `List.remove`
Generics and collections use reference types, so List<Integer> stores Integer objects. Java boxes an int when adding it and unboxes an Integer when assigning it to an int.
List has both remove(int index) and remove(Object value). The argument's static type selects the overload.
import java.util.ArrayList;
import java.util.List;
public class RemoveExample {
public static void main(String[] args) {
List<Integer> values = new ArrayList<>(List.of(10, 20, 30));
values.remove(1); // removes index 1: 20
values.remove(Integer.valueOf(10)); // removes value 10
System.out.println(values); // [30]
}
}Double equality
Primitive double comparison follows IEEE 754 rules:
Double.NaN == Double.NaNisfalse.Double.valueOf(Double.NaN).equals(Double.NaN)istrue.Double.valueOf(0.0).equals(-0.0)isfalse.
Choose the comparison based on whether you need primitive arithmetic semantics or wrapper value semantics.
The cost of boxing
Boxing can add object creation, memory use, and unboxing work. A Long accumulator in a loop may be unboxed and reboxed on every += operation. Prefer primitives for numeric calculations and LongStream, IntStream, or DoubleStream for primitive stream pipelines.
Exercise
Which overload does show(5) select when the choices are show(long) and show(Integer)?
Show answer
show(long), because primitive widening is considered before boxing.