File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make array elements final

 
Bharat Makwana
Ranch Hand
Posts: 107
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ???
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, sorry. You can use Collections.unmodifiableXYZ to create the associated List/Set/Collection
 
Remko Strating
Ranch Hand
Posts: 893
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic