Array Cheatsheet

Introduction to Arrays

Arrays are data structures that store multiple values in a single variable. Each value is accessed using an index, starting from 0. Arrays can store elements of the same data type.

Declaration and Initialization

Declaration:

int[] numbers;
String[] names;

Initialization:

numbers = new int[5]; // array of 5 integers
names = new String[]{"Alice", "Bob", "Charlie"};

Combined Declaration and Initialization:

int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};

Common Operations

  1. Accessing Elements:
    Access elements using their index.

    int firstNumber = numbers[0]; // Access first element
    String firstName = names[0];  // Access first element
  2. Modifying Elements:
    Modify elements by assigning new values to specific indices.

    numbers[1] = 10; // Change second element to 10
    names[2] = "David"; // Change third element to "David"
  3. Finding Length:
    Use the length property to get the number of elements.

    int length = numbers.length;

Traversing Arrays

  1. For Loop:

    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
  2. Enhanced For Loop (For-each):

    for (int number : numbers) {
        System.out.println(number);
    }

Array Methods (Java)

  1. Sorting:

    Arrays.sort(numbers); // Sort in ascending order
  2. Binary Search:

    int index = Arrays.binarySearch(numbers, 3); // Returns index of the element if found, otherwise returns negative value
  3. Copying Arrays:

    int[] newArray = Arrays.copyOf(numbers, numbers.length); // Copies the entire array
  4. Filling Arrays:

    Arrays.fill(numbers, 1); // Fill all elements with 1
  5. Equality Check:

    boolean isEqual = Arrays.equals(numbers, newArray); // Check if two arrays are equal

Multidimensional Arrays

  1. Declaration and Initialization:

    int[][] matrix = new int[3][3]; // 3x3 matrix
    int[][] predefinedMatrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
  2. Accessing Elements:

    int value = matrix[1][2]; // Access element at second row, third column
  3. Modifying Elements:

    matrix[0][0] = 10; // Change element at first row, first column to 10
  4. Traversing Multidimensional Arrays:

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }

Array Utilities

  1. Finding Maximum and Minimum:

    int max = Arrays.stream(numbers).max().getAsInt();
    int min = Arrays.stream(numbers).min().getAsInt();
  2. Summing Elements:

    int sum = Arrays.stream(numbers).sum();
  3. Average of Elements:

    double average = Arrays.stream(numbers).average().orElse(0.0);
  4. Joining Arrays:

    int[] firstArray = {1, 2};
    int[] secondArray = {3, 4};
    int[] joinedArray = IntStream.concat(Arrays.stream(firstArray), Arrays.stream(secondArray)).toArray();

Advanced Array Topics

  1. Jagged Arrays:
    Arrays with sub-arrays of different lengths.

    int[][] jaggedArray = new int[3][];
    jaggedArray[0] = new int[2];
    jaggedArray[1] = new int[3];
    jaggedArray[2] = new int[1];
  2. Sparse Arrays:
    Arrays mostly filled with zeros. Efficient storage techniques are used to save memory.

  3. Dynamic Arrays (ArrayLists in Java):
    If a static array size is insufficient, dynamic arrays can grow as needed.

    ArrayList<Integer> dynamicArray = new ArrayList<>();
    dynamicArray.add(1);
    dynamicArray.add(2);
    dynamicArray.add(3);

Array Limitations

  1. Fixed Size: Once declared, the size of an array cannot be changed. This can lead to wasted memory if the array is not fully utilized.
  2. Homogeneous Elements: Arrays can only store elements of the same type. For mixed data types, consider using objects or other data structures like ArrayList.

Best Practices

  1. Initialize Arrays Properly: Always ensure arrays are initialized before accessing them to avoid NullPointerException.
  2. Use Enhanced For Loop: When possible, use the enhanced for loop for readability and to avoid off-by-one errors.
  3. Boundary Checks: Always check array boundaries to prevent ArrayIndexOutOfBoundsException.

Conclusion

Arrays are fundamental data structures essential for various programming tasks. Understanding how to declare, initialize, manipulate, and traverse arrays is crucial for effective coding. By leveraging array methods and following best practices, you can efficiently work with arrays in your programs. This cheat sheet provides a solid foundation, but always refer to your specific programming language's documentation for more advanced and language-specific features.

Comments (7)