torkell: (Default)
[personal profile] torkell

Okay, so it turns out that [livejournal.com profile] talismancer's post yesterday was filler. The moral balance has swung back!

As tempting as it is to fulfill the entirety of NaBloPoMo with us commenting on each other's posts, I feel like I should actually write something. So in the interests of increasing audience participation, I shall set a Java puzzler.

The puzzler consists of the following class:

import java.util.ArrayList;

public class Foo {
    private ArrayList<Object> barList = new ArrayList<Object>();

    public void fillBarList() {
        for (int i = 0; i < 10; i++) {
            Object o = new Object();
            System.out.println("Adding " + o + " at index " + i);
            barList.add(o);
        }
    }

    public void emptyBarList() {
        for (Object o : barList) {
            System.out.println("Removing " + o);
            barList.remove(o);
        }
    }

    public static void main(String[] args) {
        Foo f = new Foo();
        f.fillBarList();
        f.emptyBarList();
    }
}

Without running it (because that would be cheating and you will be mocked for it), what do you think will happen when Foo.main() is called?

Date: 2011-11-08 08:45 am (UTC)
From: [identity profile] olego.livejournal.com
Though I'm allergic to Java, every language should result in undefined behaviour when looping over a changing object. Possible outcomes are: (1) exception, (2) only the odd-numbered elements are removed, or (3) somehow, everything is removed.

I'm leaning towards #1, though. :)

Date: 2011-11-08 09:31 am (UTC)
From: [identity profile] pteppic.livejournal.com
Not 100% sure about Java, but in c# you would get an exception for
modifying the collection while iterating.

Date: 2011-11-08 03:32 pm (UTC)
talismancer: (Default)
From: [personal profile] talismancer
It'll fill the bar with 10 objects, then empty them out again.

Except it won't, otherwise you wouldn't have posted it.

January 2026

S M T W T F S
     123
45678910
11121314151617
18192021222324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 11th, 2026 05:25 am
Powered by Dreamwidth Studios