I was making an array of objects, and wanted to run the constructor for the object on every element of the array to initialize them like so:
cells = new Cell[cols];
Arrays.fill(cells, new Cell());
But I started to doubt that it did what I wanted and sure enough Arrays.fill(Object[] o, Object val) doesn't do what I want it to. Essentially fill will run the object constructor once and point every element of the array to that object.
Testing this on StringsBuilders:
StringBuilder[] a = new StringBuilder[10];
Arrays.fill(a,new StringBuilder(""));
a[0].append("1");
System.out.println(Arrays.toString(a));
Confirmed my doubts and printed [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
.
I've always used this method with Strings and primitives and never run in to this problem because obviously it's ideal for primitives but it never caused a problem for me with strings because "modifying" them creates a completely new object. (Yes I know, I should be using StringBuilders to do that :P)
So I'm curious as to what are some other things in Java that are commonly misunderstood but people don't notice for a long time?
And just out of curiosity is there another similar Java method that fills an array with unique objects?