This question already has answers here:
Why won't declaring an array final make it immutable in Java?
(6 answers)
Why can I edit the contents of a final array in Java?
(9 answers)
Closed 9 years ago.
I tried using final keyword to array but still i can change the values, why arrays are not supporting final.
Thanks in advance
Because final applies to the array reference, not the contents.
You can modify the array content, but you can't say, reinstantiate the array.
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.
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
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.
final int[] test = new int[3];
test = new int[2]; //Error here
(final applies to the reference, not the object data)
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.
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
Related
i want to make use of an array thorughout my program but the values inside of the array would be set after going into a void. I know i can set the values by arr[0] but i have to set somewhat 10 names, as that will be very tedious i was looking for a better solution.
class sample{
String[] names=new String[10];
void main(){
names={"ram","shyam","raj","mohan","raja","adam","ramela","ramwala","ramesh","manu"};
}
}
This is what i tryed out but it give me an error saying that names={"ram"....}; is not a statement.
Help would be appreciated
You can use
names= new String[]{"ram","shyam","raj","mohan","raja","adam","ramela","ramwala","ramesh","manu"};
Array initialiser syntax can only be used at the time of variable declaration so later you have to use new keyword to initialise an array.
From Docs
An array initializer may be specified in a declaration (§8.3, §9.3,
§14.4), or as part of an array creation expression (§15.10), to create
an array and provide some initial values.
You cannot use the {...} literal declaration for arrays after they have been declared or instantiated. You will need to either assign those values during name declaration or loop through the array and assign values for each index.
String[] names = new String[10]{“ram”,...};
According to this site the syntax for creating a Java object is:
<JavaType> <variable> = new <JavaObject>();
Though you don't use any parantheses when creating an Array object and instead type brackets which contains the length of each dimension.
Example:
String[][] stringMatrix = new String[5][10];
What I am wondering is if this syntax is specifically and only for creating an Array object or I can make a custom class whose objects are created in a different way then usual
new <JavaObject>();
statement.
new keyword is used to allocate memory for the specific type, which is followed by new keyword.
MyClass obj = new MyClass();
Above line will create an object (allocate memory) for MyClass and initialize member variable by invoking default constructor.
But, below line of code will only allocate memory and initialize each element of array with default value null.
MyClass[][] objMatrix = new MyClass[5][10];
So, we are just declaring an array of size 5x10(allocating memory), but each element in array need some object reference (since, currently they have null reference). So, for that reason, you need to initialize each objMatrix array element by creating object of MyClass and assigning them to each element.
objMatrix[0][0] = new MyClass();
It is specifically for creating arrays. You're stuck with parentheses for your classes.
You can not create a custom class that changes the way the new operator works. However, there are some special cases where an object can be created without the usual new operator.
E.g.
String[] array = { "foo", "bar", "baz" };
Integer value = 42;
demonstrating that you can create arrays without the new keyword in a variable initializer, use String objects using literals and autobox primitive values to their object counterpart without the usual new syntax, but of course, this is not possible with custom types.
Another possibility to create objects without the new operator is deserializing them, which also works for custom types if they are Serializable.
Starting with Java 8, you can use constructor references if you have an appropriate context, e.g.
BigDecimal[] array = new BigDecimal[20];
Arrays.setAll(array, BigDecimal::new);
System.out.println(Arrays.toString(array));
Here, BigDecimal::new is a reference to a constructor of BigDecimal and it is implied from the context, i.e. Arrays.setAll that the function must be able to consume an int value, as the setAll method will evaluate it for every array element, passing the array index, so we initialize the array with ascending numbers in this example.
Another example would be
BigDecimal[] array = Stream.of("1.23", "4.56", "7.89")
.map(BigDecimal::new)
.toArray(BigDecimal[]::new);
System.out.println(Arrays.toString(array));
where it is implied from the context that the constructor used in the .map(BigDecimal::new) step must consume a String, as it will be evaluated for every stream element, ending up at a different constructor than in the first example.
BigDecimal is an ordinary class and these examples would work with a custom class as well, if it has matching constructors.
This question already has answers here:
Immutable array in Java
(15 answers)
Closed 8 years ago.
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.
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.
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.
This question already has an answer here:
Declaring an Array and altering its contents [duplicate]
(1 answer)
Closed 8 years ago.
List<Object[]> d = new ArrayList<Object[]>();
d.add({"A"});//compile error
Object [] arr = {"A"};//valid
I always thought that last 2 rows make equally operations and regulated by similar rules.
Who can it explain?
It's not about passing arguments to method. You can only use the {x} shorthand while initializing an array, such as your valid example. Anywhere else it's invalid. If you need to instantiate an array at a later time after initialization, you need to use new int[].
int[] a = {1,2}; // OK
int[] b;
b = {1,2}; // compiler error
I always thought that last 2 rows make equally operations and regulated by similar rules.
You were wrong.
Who can it explain?
I can't explain why you were wrong, but I can explain the syntax. The final line is valid because it is an initialisation, and initialisations have special syntax. If you had split it into a declaration and an assignment you would have got the same error in the assignment that you got in the second line. That syntax for a value simply does not exist in Java.
You can't use an array initializer as an argument.
In the first case
d.add({"A"});//compile error
You need to create a new instance of Object[] to serve as the method argument like this:
d.add(new Object[]{"A"});
In the second case, you create an array of Object. You can also do the similar thing:
Object [] arr = new Object[] {"A"};
Java lets you do the following because I think it maintains some compatibility with C/C++ array definition in the original design.
Object [] arr = {"A"};//valid
This question already has answers here:
Empty an array in Java / processing
(8 answers)
Closed 2 years ago.
I would like to remove all the elements in the String array for instance:
String example[]={"Apple","Orange","Mango","Grape","Cherry"};
Is there any simple to do it,any snippet on it will be helpful.Thanks
If example is not final then a simple reassignment would work:
example = new String[example.length];
This assumes you need the array to remain the same size. If that's not necessary then create an empty array:
example = new String[0];
If it is final then you could null out all the elements:
Arrays.fill( example, null );
See: void Arrays#fill(Object[], Object)
Consider using an ArrayList or similar collection
example = new String[example.length];
If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.
Reassign again. Like example = new String[(size)]
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Just Re-Initialize the array
example = new String[size]
or If it is inside a running loop,Just Re-declare it again,
**for(int i=1;i<=100;i++)
{
String example = new String[size]
//Your code goes here``
}**