Collections: Java and C++
A list and a map are the two containers every program needs, and both languages have them under names that look alike. The difference is what the container holds. A C++ vector<int> holds integers in one block of memory; a Java ArrayList<Integer> holds references to boxed integers, and the integers themselves are objects on the heap. That one fact explains the boxing, the iteration rule and the reference that survives a resize.
The task
A list of names with an add, a get, a size and a remove; a map of ages with a put that replaces a key and a get; a list of integers that goes through boxing; a map that keeps the insertion order; and a removal during a for-each loop, which is the mistake this page ends on. Every line prints, so the two languages can be compared without running the C++ one.
The Java version
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
public class Lists {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada", "Grace", "Alan"));
names.add("Edsger");
System.out.println("names: " + names);
System.out.println("size: " + names.size() + " get(1): " + names.get(1));
names.remove("Grace");
System.out.println("after remove: " + names);
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.put("Grace", 45);
ages.put("Ada", 37);
System.out.println("Ada: " + ages.get("Ada"));
System.out.println("keys: " + new TreeSet<>(ages.keySet()));
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
int first = numbers.get(0);
System.out.println("boxed: " + numbers + " unboxed: " + first);
Map<String, Integer> ordered = new LinkedHashMap<>();
ordered.put("b", 2);
ordered.put("a", 1);
System.out.println("ordered: " + ordered);
try {
for (String name : names) {
if (name.startsWith("A")) {
names.remove(name);
}
}
} catch (ConcurrentModificationException e) {
System.out.println("caught: " + e.getClass().getSimpleName());
}
System.out.println("still: " + names);
}
}
javac -Xlint:all -d out Lists.java
java -cp out Lists
names: [Ada, Grace, Alan, Edsger]
size: 4 get(1): Grace
after remove: [Ada, Alan, Edsger]
Ada: 37
keys: [Ada, Grace]
boxed: [1] unboxed: 1
ordered: {b=2, a=1}
caught: ConcurrentModificationException
still: [Alan, Edsger]
Boxing and the interfaces
List<Integer> numbers cannot be a List<int>, because a generic type argument is erased and has to be a reference type. numbers.add(1) boxes the literal into an Integer and int first = numbers.get(0) unboxes it again. The compiler inserts both calls, so the source reads as if the list held integers and the container holds references.
The other half is the split between an interface and a class. The variable is a List, Map or Set, and the constructor names the implementation: ArrayList, HashMap, TreeMap, LinkedHashMap. A method that takes a List works with any of them, which is the same reason a C++ function takes a pair of iterators instead of a vector.
The map in the program is a HashMap, whose iteration order is not promised, so the keys are copied into a TreeSet before they are printed. The LinkedHashMap at the end keeps the insertion order and prints b before a. A TreeMap would print them sorted, which is the third choice and the slowest of the three.
The C++ version
The C++ containers hold values and are compiled per element type. The program below is not compiled here, because the image has no g++; the text after it says what it prints and where it differs.
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names{"Ada", "Grace", "Alan"};
names.push_back("Edsger");
std::cout << "size: " << names.size() << " get(1): " << names[1] << '\n';
names.erase(names.begin() + 1);
std::map<std::string, int> ages;
ages["Ada"] = 36;
ages["Grace"] = 45;
ages["Ada"] = 37;
std::cout << "Ada: " << ages["Ada"] << '\n';
std::cout << "first key: " << ages.begin()->first << '\n';
std::vector<int> numbers{1};
const int& first = numbers[0];
for (int i = 0; i < 100; ++i) {
numbers.push_back(i);
}
std::cout << "first after the growth: " << first << '\n';
}
The vector holds strings by value, so push_back may copy and the buffer may move. The last three lines are the difference a Java programmer has to see: the reference first points into the buffer that the first push_back may have replaced, so reading it is undefined behaviour. In Java, ArrayList<Integer> holds references to objects that never move, and a reference taken from the list stays valid however often the list grows.
What differs and why
Java's containers hold references, so an element is never copied by the container and a resize copies the array of references, not the objects. The price is one object per boxed primitive and one pointer per element. C++ containers hold values, so a vector of a thousand integers is one block of four thousand bytes, and a resize copies every element unless it moves them.
Iteration reflects the same split. A Java for-each over a list uses an iterator that checks a modification count on every step, which is why a remove during the loop throws ConcurrentModificationException: the container would otherwise return a wrong element or skip one. C++ has no such check, and the equivalent mistake is undefined behaviour that may look fine in a test.
The safe removal in Java is through the iterator, iterator.remove(), or with removeIf; the same in C++ is std::erase_if or the erase-remove idiom. Both languages have a correct form, and both punish the wrong one in their own way: an exception on one side, a corrupted vector on the other.
The habit that breaks
The habit is to treat a Java container as a C++ one: to expect that == compares contents (it does not, for lists or maps either), that a HashMap has an order (it does not), and that a loop may change the container it walks. Each of the three compiles and each is wrong at run time.
The other habit is to write a key class without equals and hashCode. A HashMap finds a key by those two methods, and a class that keeps the default compares identity: two objects with the same fields are two keys, and the lookup by a newly built object misses. In C++ the map uses operator< instead, and the same mistake is a missing comparison.
The next page
The next page is exceptions: checked exceptions against throw specifications, the finally against a destructor, and the errors that are not exceptions in either language. The C++ lesson is vectors, and the Java lesson is List.
The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.
Article author: Arthur Isaev