0

I'm trying to fill a List with a unique object of my choosing, which will later be acted on. Is it just me, or is the following unintuitive:

class Event {
    void bang()
    {
        type = "bang";
    }

    String type;
}

void main()
{
    var intList= new List<int>.filled( 4, 0 );
    intList[1] = 1;

    var eventList = new List<Event>.filled( 4, new Event() );
    eventList[1].bang();    
}

At this point, intList looks like [0, 1, 0, 0], while eventList has all four slots filled with the same Event object, and its type Strings all equal "bang".

What I was hoping for was a list of four separate Event objects, what is the best way to achieve this? I can of course build the List in a for loop:

var eventList = new List<Event>( 4 );
for( int i = 0; i < 4; i++ ) {
    events[i] = new Event();
}

But this is obviously more code, time consuming and error prone to write. Not to mention potentionally slower on the VM side.

rich.e
  • 3,660
  • 4
  • 28
  • 44
  • If you don't think this is the same problem, add a comment. See also http://stackoverflow.com/questions/18258267 – Günter Zöchbauer Aug 15 '14 at 10:52
  • 1
    It is indeed the same problem, though presented a bit differently so I'll just state that the solution given is to use the `List.generate()` constructor. Thanks! – rich.e Aug 15 '14 at 10:59

0 Answers0