0

I tried using final keyword to array but still i can change the values, why arrays are not supporting final.

Thanks in advance

7 Answers7

2

Because final applies to the array reference, not the contents.

You can modify the array content, but you can't say, reinstantiate the array.

damienc88
  • 1,957
  • 19
  • 34
1

Arrays in java are reference types. When you declare an array final, you are declaring the array object reference itself final, not the elements the array contains. So while you cannot alter the array reference, you can still alter individual elements in the array.

To get the effect you want, you'll have to use Collections.unmodifiableList or something similar.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1

Consider these

final int a[]={11,2};
    int b[]={};
    a=b;// this will compile wrong 
    a[1]=1;//this will compile fine

Because if you are declaring final array then it means that the array reference can not be changed but you can obviously change the content

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

Arrays are supported, but it's no different for any other reference variables: you can change the state of the variable, but you can't change the object that the variable refers to, here the array object. For arrays, the state are the item references.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0
final int[] test = new int[3];
test = new int[2]; //Error here

(final applies to the reference, not the object data)

Manius
  • 3,594
  • 3
  • 34
  • 44
0

If you need an immutable data structure, List (you can use ArrayList if desired) is where you'll want to go. If you really need it to be an array, you'll need to create your own data structure with only getter methods.

AaronB
  • 306
  • 1
  • 4
0

final in Java affects the variable, it has nothing to do with the object you are assigning to it.

final String[] myArray = { "hi", "there" };
myArray = anotherArray; // Error, you can't do that. myArray is final
myArray[0] = "over";  // perfectly fine, final has nothing to do with it
Nagaraja
  • 581
  • 1
  • 4
  • 12