Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes How to make array elements final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to make array elements final" Watch "How to make array elements final" New topic

How to make array elements final

Bharat Makwana
Ranch Hand

Joined: May 21, 2007
Posts: 107
Hi Ranchers,

Is there any way to make individual elements of Array final ??

Suppose for primitive int array I want that nobody can change the value of that array's element,once they are assign value ???

ॐ सर्वे जना: सुखिनो भवन्तु , तथास्तु |
'May the whole world be happy, so be it'

David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Nope, sorry. You can use Collections.unmodifiableXYZ to create the associated List/Set/Collection
Remko Strating
Ranch Hand

Joined: Dec 28, 2006
Posts: 893
You could create a class in which you have a member array which you only can set by creating an instance of that class.

The class only provides a way of getting values from your array

I hope this helps.

Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Although to be built correctly the class would need to be immutable, which the above code is not eg

To make it immutable you would need to make a defensive copy of the array when it is passed in, and make the class final. (preferably the array field would be final too.

Also, as a matter of style you should throw an existing exception when one is available, so you would throw an ArrayIndexOutOfBounds rather than a IllegalArgumentException
Have you checked out Aspose?
subject: How to make array elements final
jQuery in Action, 3rd edition