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.