I was wondering if it is possible to change to change the length of a class's integer array using the Java Reflection API. If so, how?
Nope; an array is created with a fixed length.
What you can do is get close by modifying the value of the field with a copy in larger array (using Arrays.copyOf), so long as you know modifying like this won't cause any inconsistency.
/* desired length */
final int desired = ...;
/* the instance of the object containing the int[] field */
final Object inst = ...;
/* the handle to the int[] field */
final Field field = ...;
field.set(inst, Arrays.copyOf((int[]) field.get(inst), desired));
I don't think it's possible to change array length even with Reflection.
This is a reference from java tutorial.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An array is a fixed length data structure, so there is no way that it's length will be modified. Nevertheless, one can create a new array with a new fixed length in such way it can accommodate new members using
System.arrayCopy()
It is like you have an array of type T with the size of 2,
T[] t1 = new T[2]
and it is length is fixed with 2. So it can not store any more than 2 elements. But by creating new array with a new fixed length, say 5,
T[] t2 = new T[5]
So it can accommodate 5 elements now. Now copy the contents of the t1 to t2 using
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int
length)
in this case of the example,
System.arraycopy(t1, 0, t2, 0, t1.length)
Now in the new array, you have position
from t1.length to t2.length-1
is available for you to use.
I guess java will not allow you to change array length but yes you can set value at index using reflection.
import java.lang.reflect.*;
public class array1 {
public static void main(String args[])
{
try {
Class cls = Class.forName(
"java.lang.String");
Object arr = Array.newInstance(cls, 10);
Array.set(arr, 5, "this is a test");
String s = (String)Array.get(arr, 5);
System.out.println(s);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
Related
When I run this code on cmd prompt with statement :
java Test A
output is
a
b
c
Wasn't it suppose to result in an error since dimension of args is 1 whereas dimension of x is 3 (args=x).
class Test
{
public static void main(String args[])
{
String[] x={"a","b","c"};
args=x;
for(String i: x)
{
System.out.println(i);
}
}
}
well, the array variable in java is only a reference, so if you give it another reference for a String array it will accept it, so the range of values the array variable(args) accepts is the references to String arrays at memory, it's like changing the value of an integer from 1 to 3, it's ok because they're both valid, and in the range that the integer accepts.
It will not result in an error because your object is not final and you are not changing the array object.
here
double[] data = new double[5]{2, 4, 5, 6, 8} // data can change but the instance of the class cant change
double[] data = new double[7] // here you are changing the data but not the object i.e the created instance of the object does not change but the instance the data(the variable) is holding changes
I hope you got your answer
We can determine the length of an ArrayList<E> using its public method size(), like
ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();
Similarly we can determine the length of an Array object using the length property
String[] str = new String[10];
int size = str.length;
Whereas the size() method of ArrayList is defined inside the ArrayList class, where is this length property of Array defined?
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Resources:
JLS - Arrays
It's "special" basically, with its own bytecode instruction: arraylength. So this method:
public static void main(String[] args) {
int x = args.length;
}
is compiled into bytecode like this:
public static void main(java.lang.String[]);
Code:
0: aload_0
1: arraylength
2: istore_1
3: return
So it's not accessed as if it were a normal field. Indeed, if you try to get it as if it were a normal field, like this, it fails:
// Fails...
Field field = args.getClass().getField("length");
System.out.println(field.get(args));
So unfortunately, the JLS description of each array type having a public final field length is somewhat misleading :(
It's defined in the Java language specification:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
Since there is a limitless number of array types (for every class there is a corresponding array type, and then there are multidimensional arrays), they cannot be implemented in a class file; the JVM has to do it on the fly.
Even though this is not a direct answer to the question, it is an addition to the .length vs .size() argument. I was researching something related to this question so when I came across it I noticed that the definition(s) provided here
The public final field length, which contains the number of components of the array.
is not "exactly" correct.
The field length contains the number of available places to put a component, not the number of components present in the array. So it represents the total available memory allocated to that array, not how much of that memory is filled.
Example:
static class StuffClass {
int stuff;
StuffClass(int stuff) {
this.stuff = stuff;
}
}
public static void main(String[] args) {
int[] test = new int[5];
test[0] = 2;
test[1] = 33;
System.out.println("Length of int[]:\t" + test.length);
String[] test2 = new String[5];
test2[0] = "2";
test2[1] = "33";
System.out.println("Length of String[]:\t" + test2.length);
StuffClass[] test3 = new StuffClass[5];
test3[0] = new StuffClass(2);
test3[1] = new StuffClass(33);
System.out.println("Length of StuffClass[]:\t" + test3.length);
}
Output:
Length of int[]: 5
Length of String[]: 5
Length of StuffClass[]: 5
However, the .size() property of the ArrayList does give the number of elements in the list:
ArrayList<Integer> intsList = new ArrayList<Integer>();
System.out.println("List size:\t" + intsList.size());
intsList.add(2);
System.out.println("List size:\t" + intsList.size());
intsList.add(33);
System.out.println("List size:\t" + intsList.size());
Output:
List size: 0
List size: 1
List size: 2
it's public final field , which contains the number of components of the array (length may be positive or zero)
An array thus has the same public fields and methods as the following class:
class A implements Cloneable, java.io.Serializable {
public final int length = X;
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
}
}
more info at
10.7 Array Members
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
To answer it as it-is, where is this length property of array defined? In a special Object header.
Easy to see via JOL
int [] ints = new int[23];
System.out.println(ClassLayout.parseInstance(ints).toPrintable());
One of the lines from this output is going to be:
OFFSET SIZE TYPE DESCRIPTION
16 4 (object header) 17 00 00 00 (00010111 00000000 00000000 00000000) (23)
Usually Objects have two headers (mark and klass), arrays have one more that always occupy 4 bytes in length, as size is an int.
The keyword length acts like a data filed defined. When using in an array, we can use it to access how many elements in an array. Regarding to String[], we can invoke length() method defined in String class. With regard to ArrayList, we can use size() method defined in ArrayList. Note that when creating an array list with ArrayList<>(capacity), the initial size() of this array list is zero since there is no element.
I'm very new to Java programming and wanted to try my hand at a little bit outside of my classes. I've created a class that will manipulate arrays, so I set up a private array with no size allocated to it. In a public constructor, how do I set the size of this array?
public ClassName()
{
arr = new int[10];
}
Remember that the Constructor is the method called when an object is instantiated. The Constructor must be a method with no return type and the same name as the class. You could even take in parameters if you'd like to(say a size variable), then create a new array based on the size.
For instance, you could do this:
public ClassName(int size)
{
arr = new int[size];
}
Now when in your tester class, you could create a new object using that constructor.
ClassName c = new ClassName(5);
Which creates a new object with an array of size 5 as a class variable. Hope this helped!
Edit: I should add; if you do not specify a constructor, Java will do it for you, but it will do nothing.
Just like in must of the languages.
example:
anArray = new int[10]; //10 - array size, int is the array type
read about JAVA Arrays
We can determine the length of an ArrayList<E> using its public method size(), like
ArrayList<Integer> arr = new ArrayList(10);
int size = arr.size();
Similarly we can determine the length of an Array object using the length property
String[] str = new String[10];
int size = str.length;
Whereas the size() method of ArrayList is defined inside the ArrayList class, where is this length property of Array defined?
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Resources:
JLS - Arrays
It's "special" basically, with its own bytecode instruction: arraylength. So this method:
public static void main(String[] args) {
int x = args.length;
}
is compiled into bytecode like this:
public static void main(java.lang.String[]);
Code:
0: aload_0
1: arraylength
2: istore_1
3: return
So it's not accessed as if it were a normal field. Indeed, if you try to get it as if it were a normal field, like this, it fails:
// Fails...
Field field = args.getClass().getField("length");
System.out.println(field.get(args));
So unfortunately, the JLS description of each array type having a public final field length is somewhat misleading :(
It's defined in the Java language specification:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
Since there is a limitless number of array types (for every class there is a corresponding array type, and then there are multidimensional arrays), they cannot be implemented in a class file; the JVM has to do it on the fly.
Even though this is not a direct answer to the question, it is an addition to the .length vs .size() argument. I was researching something related to this question so when I came across it I noticed that the definition(s) provided here
The public final field length, which contains the number of components of the array.
is not "exactly" correct.
The field length contains the number of available places to put a component, not the number of components present in the array. So it represents the total available memory allocated to that array, not how much of that memory is filled.
Example:
static class StuffClass {
int stuff;
StuffClass(int stuff) {
this.stuff = stuff;
}
}
public static void main(String[] args) {
int[] test = new int[5];
test[0] = 2;
test[1] = 33;
System.out.println("Length of int[]:\t" + test.length);
String[] test2 = new String[5];
test2[0] = "2";
test2[1] = "33";
System.out.println("Length of String[]:\t" + test2.length);
StuffClass[] test3 = new StuffClass[5];
test3[0] = new StuffClass(2);
test3[1] = new StuffClass(33);
System.out.println("Length of StuffClass[]:\t" + test3.length);
}
Output:
Length of int[]: 5
Length of String[]: 5
Length of StuffClass[]: 5
However, the .size() property of the ArrayList does give the number of elements in the list:
ArrayList<Integer> intsList = new ArrayList<Integer>();
System.out.println("List size:\t" + intsList.size());
intsList.add(2);
System.out.println("List size:\t" + intsList.size());
intsList.add(33);
System.out.println("List size:\t" + intsList.size());
Output:
List size: 0
List size: 1
List size: 2
it's public final field , which contains the number of components of the array (length may be positive or zero)
An array thus has the same public fields and methods as the following class:
class A implements Cloneable, java.io.Serializable {
public final int length = X;
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.getMessage());
}
}
}
more info at
10.7 Array Members
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
To answer it as it-is, where is this length property of array defined? In a special Object header.
Easy to see via JOL
int [] ints = new int[23];
System.out.println(ClassLayout.parseInstance(ints).toPrintable());
One of the lines from this output is going to be:
OFFSET SIZE TYPE DESCRIPTION
16 4 (object header) 17 00 00 00 (00010111 00000000 00000000 00000000) (23)
Usually Objects have two headers (mark and klass), arrays have one more that always occupy 4 bytes in length, as size is an int.
The keyword length acts like a data filed defined. When using in an array, we can use it to access how many elements in an array. Regarding to String[], we can invoke length() method defined in String class. With regard to ArrayList, we can use size() method defined in ArrayList. Note that when creating an array list with ArrayList<>(capacity), the initial size() of this array list is zero since there is no element.
I am having a little trouble understanding the concept of final in Java.
I have a class that follows:
public class MyClass
{
private int[][] myArray; // intended to be changed
private final int[][] MYARRAY_ORIGINAL; // intended to be unchangable
public MyClass(int[][] array)
{
myArray = array;
MYARRAY_ORIGINAL = array;
}
}
I was under the understanding that final would make MYARRAY_ORIGINAL read only. But I have tried editing myArray, and it edits MYARRAY_ORIGINAL as well. My question is, in this context, what exactly does final do? And for extra credit, how can I copy the array passed through the constructor into MYARRAY_ORIGINAL so that I can have 2 arrays, one to edit, and one that will remain preserved?
Your final MYARRAY_ORIGINAL is indeed read only: you can't assign a new value to the MYARRAY_ORIGINAL reference in other side than class constructor or attribute declaration:
public void someMethod() {
//it won't compile
MYARRAY_ORIGINAL = new int[X][];
}
The values inside the array are not final. Those values can change anytime in the code.
public void anotherMethod() {
MYARRAY_ORIGINAL[0][0] = 25;
//later in the code...
MYARRAY_ORIGINAL[0][0] = 30; //it works!
}
If you indeed need a List of final elements, in other words, a List whose elements can't be modified, you can use Collections.unmodifiableList:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
The last piece of code was taken from here: Immutable array in Java
In case of Objects, final makes reference can't be changed, but object state can be changed.
That is the reason why you are able to change values of final MYARRAY_ORIGINAL
MYARRAY_ORIGINAL is indeed read only variable. Your array reference can not be assigned a new value nor for their length of the arrays can be changed. A final variables initialization can be deferred till the constructors is called. If one tries to modify the reference of the final variable, compiler will throw an error message. But what is possible is, one can edit the elements of the MYARRAY_ORIGINAL and of the myArray i.e one can change the state of the object assigned to a final variable. For example
Class A {
final int[] array;
public A() {
array = new int[10] // deferred initialization of a final variable
array[0] = 10;
}
public void method() {
array[0] = 3; // it is allowed
array = new int[20] // not allowed and compiler will throw an error
}
}
To understand more on final please take a look at Java Language Specification on final variable.
Final does not mean 'read-only' per se, but more so "safe publication' for other threads than the one to which it is defined. Another aim of 'final' is that it ensures the latest object available in a multi-thread environment.
Secondly, if you define something as "final", for example:
private final int[][] MYARRAY_ORIGINAL;
The reference is "final", but not the object itself. A much better way to understand it would be this:
public static final List myList = new ArrayList();
Now I can access myList from any other threads - I can modify it (add to it); but I cannot
(a) Declare it again - myList = new ArrayList();
(b) Assign it another list - myList = anotherList;
The context for final I would see best, in a multiple-thread scenario.
Bonus: to answer your question, you cannot make a 'readonly' array, you will have to manage that yourself (as final, only maintains 'read-only' to reference not object)
You can use the method System.arraycopy to make a copy of the array as follows -
int[][] source = {{1,2},{3,4}};
int[][] copy = new int[source.length][];
System.arraycopy(source, 0, copy, 0, source.length);
Also, you some problem with your code regarding what you are trying to do. If you look at the constructor
public MyClass(int[][] array) { //something else passes the array
myArray = array;
MYARRAY_ORIGINAL = array; // you are just keeping a reference to it can be modified from outside
}
If you really want nobody to modify the values in that array MYARRAY_ORIGINAL, you should make a copy of the source array that comes comes from outside.
public MyClass(int[][] array) {
myArray = array; //make a copy here also if you don't want to edit the argument array
MYARRAY_ORIGINAL = new int[array.length][];
System.arraycopy(array, 0, MYARRAY_ORIGINAL, 0, array.length);
}
Now you shouldn't have to worry about the array's being modified from outside.