-1

I have following piece of code :

final int[] a = new int[5];
a[0] = 10;
a[0] = 5;

this code is perfectly fine as I am modifying the object and not the reference but now I want something like this :

int[] a  = final new int[5];

so line 3 above will fire an error that I am trying to change immutable array. Is there any simple way to do it? There is a function in collections but I don't want to use any type of collection.

Roman C
  • 49,761
  • 33
  • 66
  • 176
user1079065
  • 2,085
  • 9
  • 30
  • 53
  • 1
    Are you asking how to make array immutable? If so then the answer is: you can't (only exception is array of size `0` because it can't have any elements so it can't be changed, so it may be considered immutable). – Pshemo Jul 12 '14 at 16:31
  • 1
    "I dont want to use any type of collection" -- why? – arshajii Jul 12 '14 at 16:38
  • that is the project requirement... can't help it... – user1079065 Jul 12 '14 at 16:43

2 Answers2

2

Is there any simple way to do it?

With a plain array, no. Arrays will always be mutable, so if you want this functionality you'll have to wrap an array and provide a mechanism for reading it (and not one for writing to it). There are already utilities in the standard JDK classes that can do this for you, like in Collections as you state.

You can, for example, use an unmodifiable list as returned by Collections.unmodifiableList instead. For example, to create an unmodifiable list containing 1, 2 and 3:

List<Integer> a = Collections.unmodifiableList(Arrays.asList(1, 2, 3));

Without some sort of wrapper (be it standard or not), what you're asking for can't be done.

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

If you declare:

final int[] myarray = new int[5];

it will not make your array immutable as you expect. The reference myarray will be final, but contents of this array can be changed.

As you do not want to use Collections Framework, make your own wrapper class over your array, to prevent modifying it's contents. And it will make your array immutable.