Last active
December 23, 2015 07:49
-
-
Save gabrieloshiro/6603386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Include this if you want to use toString method to print the array | |
import java.util.Arrays; | |
public class LearningArray { | |
public static void main(String[] args) { | |
// Creating a reference to an Array of integers | |
int[] iArray; | |
// Allocating 10 integers in memory | |
iArray = new int[10]; | |
// Set the contents of each element of the array with their index | |
// For an array with 10 elements first index is 0 and last is 9 | |
iArray[0] = 0; | |
iArray[1] = 1; | |
iArray[2] = 2; | |
iArray[3] = 3; | |
iArray[4] = 4; | |
iArray[5] = 5; | |
iArray[6] = 6; | |
iArray[7] = 7; | |
iArray[8] = 8; | |
iArray[9] = 9; | |
// Print array | |
System.out.println(Arrays.toString(iArray)); | |
// Deallocating array, Garbage Collector will take care of it ;-) | |
iArray = null; | |
// Creating a constant array | |
int[] iArray2 = { | |
10, 20, 30, | |
40, 50, 60, | |
70, 80, 90 | |
}; | |
// Find out how big my array is | |
System.out.println(iArray2.length); | |
} | |
} | |
// What if I don't import Arrays? | |
// Using System.out.println(iArray.toString()); will call toString from Java Object which will print the hash code of the object. Not very user friendly. | |
// Do I have to allocate the array before using it? | |
// Yes. Otherwise you'll get a NullPointerException. BOOM! | |
// What if I want change my array dinamically by adding and removing elements? | |
// Use something else. Like Collections framework. | |
// Can I instantiate an array like this: | |
// int iArray[]; | |
// ? | |
// Yes. But according to Java tutorials "this form is discouraged". | |
// Can I change the size of my array once it was instanciated? | |
// No. Length is a final property that holds the number of positions of an array. | |
// Please note that it is not the number of elements, because if there is a null | |
// element in an array it counts as a position but not as an element. | |
// A possible solution is to create another array, with the new desired size and copy the elements | |
// from the old array to the new array. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment