Using collection size in for loop comparison

Okay, here is an excerpt from the JDK sources (src.zip in the JDK folder):

public int size() {
    return size;
}

This is from ArrayList, but I think other collections have similar implementations. Now if we imagine that the compiler inlines the size() call (which would make perfect sense), your loop turns into this:

for(int i=0;i<list.size;i++)
// ...

(Well, let's forget that the size is private.) How does compiler checks if the collection was modified? The answer that it doesn't and doesn't need to do so because the size is already available in the field, so all it has to do is to access the size field on each iteration, but accessing an int variable is a very fast operation. Note that it probably calculates its address once, so it doesn't even have to dereference list on each iteration.

What happens when the collection is modified, say, by the add() method?

public boolean add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

As you can see, it just increases the size field. So the compiler doesn't actually need to do anything to ensure it has access to the latest size. The only exception would be that if you modify the collection from another thread you need to synchronize, otherwise the loop thread may see its local cached value of size which may or may not be updated.

Answer:1

Calling the size() method of a collection is just returning an integer value that is already kept track of. There isnt much of a time difference because size() isnt actually counting the number of items but instead the number of items are kept track of when you add or remove them.

Answer:2

How to build the following PSQL query to update multiple records using jOOQ 3.10.x? UPDATE users SET name = s.name, city = s.city FROM users_staging s WHERE users.id = s.id;

I would like to parse two separate strings "1982" and "SEP" into a java.time.YearMonth object. java.time.YearMonth.parse("1978 SEP", java.time.format.DateTimeFormatter.ofPattern("yyyy LLL")) gives ...

I compiled my program and I got the following error. How should I resolve it? Note: ClientThreadClients.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details.

We are developing a Java application to be run on Linux environments (Ubuntu for now) which communicates with a piece of hardware. Said hardware uses a .so library made available by the manufacturer ...