5

I don't have a use case but out of curiosity, is there a way to make individual references in an array final?

final Integer[] intArray = new Integer[10];  // doesn't make individual references final
final intArray[0] = Integer.valueOf(1);  // something like this is not allowed
Nitin Dandriyal
  • 1,559
  • 11
  • 20
  • 1
    No, `Syntax error, insert "EnumBody" to complete BlockStatement` – Soumitri Pattnaik May 28 '15 at 06:26
  • 3
    What you are asking for is known as *immutability*. Unfortunately, this cannot be achieved for arrays (which allow direct access to elements without going through a method ) – TheLostMind May 28 '15 at 06:33
  • Arrays don't have structure, so no, you can never declare different modifiers for one element than for another. If you want to have structure in your data, don't use arrays: make a class with fields. And make one of these fields `final`. – Erwin Bolwidt May 28 '15 at 06:36
  • I know what is immutability, I am asking from the perspective of Java specs – Nitin Dandriyal May 28 '15 at 06:37
  • @NitinDandriyal - Nope. *Arrays* are *special primitive types* with no methods to *control* access to their cells / elements. So, it would be almost impossible to bring about immutability – TheLostMind May 28 '15 at 07:02
  • @TheLostMind Arrays are homogeneous aggregates with identity(reference) which is not the case with hardwired primitive types: byte, short, int, long, float, double, char, and boolean, my question was from a language spec perspective. Language doesn't provide it I know, and I know that I can use `Collections`, What I was fishing for was a smart alternative which I think isn't there. So let's close it here. Thanks – Nitin Dandriyal May 28 '15 at 07:25
  • @NitinDandriyal Of course there is a smart alternative: make a class. Don't abuse arrays to store structured data. Only use an array if each entry has exactly the same generic meaning as another. If you every refer to particular entries in an array, like `array[2]` or `array[5]` (rather than looping over `array[i]`), you're most likely doing something wrong and you should have created a class instead. – Erwin Bolwidt May 28 '15 at 07:45
  • @ErwinBolwidt Yes I know, but the classes have their own issues, while writing low-latency applications (work with very large data sets while avoiding long GC pauses) Refer: http://cr.openjdk.java.net/~jrose/values/values-0.html, http://mechanical-sympathy.blogspot.sg/2012/10/compact-off-heap-structurestuples-in.html // no comments further – Nitin Dandriyal May 28 '15 at 08:06

0 Answers0