Array - Java

  • Basic
    • Collection of similar data type elements
  • Commands
    • int var[]; => Declaring an Array
    • int var[n]; => Declaring an Array of size "n"
    • int[] var; => Declaring an Array
    • int[] var = {val1, val2, val3}; => Initializing an Integer Array, We use this method when we already know the elements of the Array
    • int[] var = new int[n]; => Initializing an Integer Array of size "n"
    • var[n]; => Returns the value at that Index
    • var[n] = val; => Assign a value at that Index
    • var.length; => Returns length of Array, It is a property of a Array not a Function
    • Array.sort(var); => Sorts the Array in ascending order using sort Function from Array Class
    • Initializing an 2D Integer Array
        int[][] var = {{val1, val2, val3}, {val4, val5, val6}
      
    • var[n1][n2]; => Accessing value of 2D Array

ArrayList


  • Basic
    • Like Array but of Dynamic nature
  • Commands
    • Initialize an ArrayList of Integer
        ArrayList<Integer> var = new ArrayList<Integer>();
      
    • Initialize an ArrayList of String
        ArrayList<String> var = new ArrayList<String>();
      
    • Initialize an ArrayList of Integer with values
        ArrayList<Integer> var = new ArrayList<Integer>(Array.asList(val1, val2, val3));
      
    • var[n] = val => Insert a value
    • var.size(); => Returns length of Array
    • var.add(val) => Insert the given value at the end
    • var.add(n, val) => Insert the value at index "n"
    • var.sort(Comparator.naturalOrder()) => Sorts the Array in ascending order
    • var.sort(Comparator.reverseOrder()) => Sorts the Array in descending order
    • System.out.println(var) => Print all elements of ArrayList
Share: