Monday, April 21, 2008

Const Array create how?

JAVA Code:
final int array[]={1,2,4};
array[0]=5;
System.out.println(array[0]);

output: 5 // Becoz final keyword will not yield the desired effect, because it will just make the variable not be able to point to another object (like a const pointer) - it will not make the object referred by it constant.


JAVA Code: //to make an constant Array
import java.util.*;
public class Test
{
static Object array[] = {new Integer(1), new Integer(2), new Integer(4)};
public static final List CONST =
Collections.unmodifiableList(Arrays.asList(array));
public static void main(String args[])
{
CONST.set(0, new Integer(5));
System.out.println(CONST.get(0));
}
}
JAVA Code:Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.set(Collections.java:1141)
at Test.main(Test.java:12)

No comments: