Moe's Tech Blog

[JAVA] Notes about Array 본문

Java/Notes

[JAVA] Notes about Array

moe12825 2022. 8. 24. 00:27
  • Array is fixed in size (its size cannot be modified)
  • 2D array is declared by adding double square parenthesis [][] in front of data type
    • i.e. int[][] twoDIntArray, String[][] twoDStringArray, double[][] twoDDoubleArray
  • 2D array can be given initial values by using curly brackets
double[][] doubleValues = {
  {1.5, 2.5, 3.5},
  {0.2, 0.3, 0.4}
}
String[][] = {
  {"hello", "world"},
  {"2D Array", "in", "Java", "is", "cool"}
}
  • 2D array with empty values can be created by new DATA_TYPE[ROW_SIZE][COLUMN_SIZE]
int[][] subMatrix = new int[2][2];
  • already defined 2D array can be modified by adding curly braces in front of data type
double[][] doubleValues = {{1.5, 2.6, 3.7}, {7.5, 6.4, 5.3}, {9.8,  8.7, 7.6}, {3.6, 5.7, 7.8}};

doubleValues = double[][] {{0.5, 0.6, 0.7}, {3.5, 4.4, 7.3}, {10.8,  3.7, 4.6}, {7.6, 1.7, 3.8}};
  • To print the array in string, use Arrays.deepToString method
System.out.println(Arrays.deepToString(subMatrix));

// [[5, 5], [10, 0]]

Array List

 

  • array size can be modified dynamically
  • allows flexibility by being able to both add and remove elements
// import the ArrayList package
import java.util.ArrayList;

// create an ArrayList called students
ArrayList<String> students = new ArrayList<String>();

 

 

References