One of the key points of confusion for people unfamiliar with Java is the distinction between true object types, like Integer
, and "primitive" types, like int
. This is made worse by the collection types, like ArrayList
, which needs to hold a true object type, but can't hold a primitive. A generic ArrayList<Integer>
is valid, but ArrayList<int>
won't compile. Fortunately for everyone, Java automatically "boxes" types- at least since Java 5, way back in 2004- so integerList.add(5)
and int n = integerList.get(0)
will both work just fine.
Somebody should have told that to Alice's co-worker, who spends a lot of code to do some type gymnastics that they shouldn't have:
try {
ps = conn.prepareStatement(SQL_GET_LOT_WORKUP_STATUSES);
ps.setLong(1, _lotId);
rs = ps.executeQuery();
while (rs.next()) {
result.add(new Integer(rs.getInt(1)));
}
}
finally {
CloseUtil.close(ps,rs);
}
// instatiate a the array
_workupStatuses = new int[result.size()];
// convert the integers to ints
for (int h=0; h<result.size(); h++) {
_workupStatuses[h] = ((Integer)result.get(h)).intValue();
}
This runs a query against the database, and then iterates across the result to populate a List
type with integers, and right away we're getting into confused territory. rs.getInt
returns an int
primitive, which they manually box with new Integer
, and stuff into the List
. And look, I wouldn't really call that a WTF, but it's what they do next that leaves me scratching my head.
They initialize a private member, _workupStatuses
to a new array of int
s. Then they copy every integer from the result
collection into the array, first by casting the get
return value to Integer
, then by pulling off the intValue
.
In the end, this whole dance happens because Java ResultSet
types open cursors on the database side and thus don't have the capacity to tell you how many rows they returned. You need to iterate across each record until it runs out of results. That's why they populate an intermediate list. Then they can check the size
and create an array, but that itself is a big why. I'm not going to say that using arrays in Java is an instant anti-pattern, but it's always something to be suspicious of, especially when you're holding result sets. It's probably a premature optimization: the key performance distance is on insertions where an ArrayList
may need to resize and copy its internal backing store.
My suspicion, however, is that this code falls into the category of "C programmer forced to do Java". They're comfortable with an array of integers, which is covers 90% of the data types you use in C but a dynamic, complicated data structure is horrifying to them. So they use it when they absolutely have to, and then throw it away as quickly as they can to get back to what they're familiar with.
Your journey to .NET 9 is more than just one decision.Avoid migration migraines with the advice in this free guide. Download Free Guide Now!