This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any shortcut to initialize all array elements to zero?
How to Initializing a normal 2D array with zeros(all shells should have zero stored) without using that old looping method that takes lots of time .My code wants something that should take very less time but via looping method my time limit exceeds.
The important thing to realise here is that if you're storing primitives then the default value is zero (scroll down to the Default Values section). This applies to array initialisation as well as simple variable initialisation, and consequently you don't have to initialise the array contents explicitly to zero.
If you have to reset an existing structure, however, then you'd have to loop through the structure, and you may be better off initialising a new instance of your array structure.
Note that if you're creating an array or arrays, obviously you have to initialise the first array with the contained array.
Related
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}
This question already has answers here:
Using a long as ArrayList index in java
(7 answers)
Closed 2 years ago.
I am trying to get an element from a list List<Class> listofitems, and I have a globale variable position of type long. I would like to perform listofitems.get(position) but it doesnt allow me to do so since get takes int as argument. If I want to keep the type of position as long, if there are any other way to do this? (any other way besides casting position to int)?
If you wanted to do this, you'd have to construct a class that holds a grouping of lists to represent your data. You can write your own access method that splits your long into smaller ints, to access the right position in your list.
See this answer: Using a long as ArrayList index in java
This is a point where memory must be consulted through the Unsafe api. Incase of list/arrays greater than Integer.MAX_VALUE here is the link. NOTE:
Write your own implementation of the list/array.
Unsafe is literally unsafe.
Such an implementation would require long indices.
Speed will abundant.
If what you have is a List<Class>, and it cannot be changed to another type, then there is nothing you can do besides convert that long to an int. There is no way to take an arbitrary List and call get with anything but an int.
How can I add an element to an array while expanding the length of the array by one unit without using ArrayList? I'm a student, and it's forbidden for the assignment.
I have written a method that does it (sort of). It increments the array length every time its called but it only saves the last input parameter tot the very last element (every other element is made null when I create the new array with new length). The method is called in my constructor that makes an instance of an object from every line scanned in a text file, and I am supposed to add this line to an instance array.
You can't.
You can only create a new array which is longer than the old one. Other references of your program, already having a reference to the old array, are not affected and keep the old sized array.
This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Java native array lengths
(6 answers)
Closed 9 years ago.
Let's say I create an array of ints with length 10, i.e.
int[] array = new int[10];
At some point in my code, I want to compare the value of an int variable, let's call it var, with the length of the array.
I would like to know if this piece of code:
if(var == array.length) { // stuff }
and this piece of code:
if(var == 10) { // stuff }
which do exactly the same thing, have also the same performance.
In other words, I would like to know the internal mechanics that the JVM (?) uses to find the length of the array (I don't say "to return" since length is a field, not a method). Does it make use of iteration? Because if it does, then the 2nd piece of code would be faster than the 1st one.
EDIT: Similar question regarding array.length cost (even though focusing more to its use in for loops):
What is the Cost of Calling array.length
.length is a property, so it would not do iteration for sure. Still, the value of the property is, naturally, fetched at runtime, meaning that the second solution will be a little bit faster (as this is comparison with constant).
Still the first implementation is far more preferable:
This makes your code quite more maintainable
You can alter the length of the array only at one place
You will never feel the performance difference unless you pass through this if litterally millions of times in a second.
EDIT By the way you can yourself tell this is a property - there are no braces after the call. I at least do not know of a way in java to make property access do additional computation, but just retrieving its value.
.length is a property of the array, not a function. Thus, the result would be available immediately, with no iteration necessary.
From the Java Doc
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.
length is an final field of array, so no iterations are required while writing following code.
if(var == array.length) { // stuff }
And it is good coding practice indeed.
The length property of an array is extracted in constant (O(1)) time - there is no iteration needed. It's also good practice to use this.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Make copy of array Java
I'm a beginner at Java and I need to copy the contents of one array into another variable. However, Java always passes the array by reference instead of by value.
Here's what I mean if that was confusing:
int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
System.out.print(test[i]); // Prints 1284 instead of 1234
In this example, I don't want the value of test to change. Is this possible without using any of the more advanced features of Java such as ArrayList and Vectors?
Edit: I tried System.ArrayCopy and test.clone(), but they still don't seem to work.
Here's my actual code:
temp_image=image.clone();
for(int a=0;a<image.length;a++)
for(int b=0;b<image[0].length;b++)
image[a][b]=temp_image[image.length-1-a][b];
Basically I'm trying to flip the "image" upside down. Is there an error somewhere in the code?
You need to clone your array.
test2=test.clone();
Starting in Java 6 you can use Arrays.copyOf:
test2 = Arrays.copyOf(test, test.length);
For what you're looking to do, test.clone() is fine. But if you wanted to do a resize, copyOf allows you to do that. I think in terms of performance it
System.arraycopy would give even more options if you needed them.
Because test and test2 are both pointers to the same array, you are changing the value of both test and test2 with your statement test2[2]=8
A solution would be to copy the contents of test into test 2 and change the value at the specific index of test2.
for (int i=0,i<test.length,i++)
test2[i]=test[i]
//Now both arrays have the same values
test2[2]=8
for (int j=0,j<test.length,j++)
System.out.print(test[i])
System.out.println()
System.out.print(test2[i])
Will output
1 2 3 4
1 2 8 4