Forum Stats

  • 3,826,362 Users
  • 2,260,636 Discussions


Issues with Arrays.fill (𝑢𝒃𝒋𝒆𝒄𝒕[] 𝒂, 𝑢𝒃𝒋𝒆𝒄𝒕 val) method

Lovely Jain
Lovely Jain Member Posts: 2 Green Ribbon
edited Jun 18, 2022 4:24PM in Java Programming

The method just assigns the reference to the respective indexes.Β 

π’‘π’–π’ƒπ’π’Šπ’„ π’”π’•π’‚π’•π’Šπ’„ π’—π’π’Šπ’… π’‡π’Šπ’π’(𝑢𝒃𝒋𝒆𝒄𝒕[] 𝒂, 𝑢𝒃𝒋𝒆𝒄𝒕 𝒗𝒂𝒍) {

  𝒇𝒐𝒓 (π’Šπ’π’• π’Š = 0, 𝒍𝒆𝒏 = 𝒂.π’π’†π’π’ˆπ’•π’‰; π’Š < 𝒍𝒆𝒏; π’Š++)

   𝒂[π’Š] = 𝒗𝒂𝒍;

Β }

This can cause some unexpected behaviour. For eg.Β 

// 𝒄𝒓𝒆𝒂𝒕𝒆 π’‚π’“π’“π’‚π’š 𝒐𝒇 π‘¨π’“π’“π’‚π’šπ‘³π’Šπ’”π’•

π‘¨π’“π’“π’‚π’šπ‘³π’Šπ’”π’•<π‘°π’π’•π’†π’ˆπ’†π’“> π’π’Šπ’”π’•[] = π’π’†π’˜ π‘¨π’“π’“π’‚π’šπ‘³π’Šπ’”π’•[5];

π‘¨π’“π’“π’‚π’šπ’”.π’‡π’Šπ’π’(π’π’Šπ’”π’•, π’π’†π’˜ π‘¨π’“π’“π’‚π’šπ‘³π’Šπ’”π’•());

// 𝒂𝒅𝒅 π’†π’π’†π’Žπ’†π’π’•π’”




List will beΒ  [ [0,1,2], [0,1,2], [0,1,2], [0,1,2], [0,1,2]] which is definitely what user wanted or expected and it can cause serious issues which will be tough to debug.

I wonder why the behaviour is so. One who is using Arrays.fill would like to do some operation on objects. If object is mutable, then it will cause such problem. If it's not, it will be like for read-onlyΒ  purpose we are creating this array which doesn't makes sense to me.

I initially thought they should clone it, which is not possible for custom classes or classes which don't override clone method. Obviously, creating object using new isn't possible. Can methods like newInstance be used??Β 

It looks like Arrays.fill method for object array initialization is less useful & more dangerous to use.Β