Maison > Java > javaDidacticiel > Introduction aux tableaux en Java

Introduction aux tableaux en Java

Susan Sarandon
Libérer: 2024-10-09 10:11:02
original
795 Les gens l'ont consulté

Introduction to Arrays in Java

Programming often involves managing and manipulating large sets of data, for which efficient and effective data structures are crucial. Arrays are a fundamental data structure in computer science and provide a means to store a fixed-size sequence of elements of the same type. In this blog, we'll take an in-depth journey through arrays in Java: understanding what they are, their syntax, how to operate on them, and their memory management.

Why Do We Need Arrays?

When working with variables in Java, you can declare and initialize each one individually, such as:

java
int a = 19;
String name = "John Doe";
Copier après la connexion

However, this approach becomes inefficient if you need to handle multiple values of the same type. For instance, if you were to store multiple roll numbers or names, hard coding each value isn't practical. Arrays come in handy by allowing you to store a collection of values efficiently. For instance, if you need to store five roll numbers, you can utilize arrays.

What Are Arrays?

An array is essentially a collection of data items of the same type. Arrays can store primitive data types like integers, floats, and characters, as well as objects. For example:

int[] rollNumbers = new int[5];
String[] names = {"Alice", "Bob", "Charlie"};
Copier après la connexion

Syntax of Arrays

The syntax for declaring an array in Java is straightforward:

dataType[] arrayName = new dataType[size];
Copier après la connexion

For example, to create an array of five integers:

int[] rollNumbers = new int[5];
Copier après la connexion

Alternatively, you can declare and initialize an array in a single line:

int[] rollNumbers = {23, 55, 9, 18, 45};
Copier après la connexion

Characteristics of Arrays

Homogeneous Elements

In an array, all elements must be of the same type. You can't mix types within a single array; for example:

int[] nums = {1, 2, "three"}; // Will cause a compile-time error
Copier après la connexion

Fixed Size

Once an array is created, its size is fixed. You cannot expand or shrink its size. This constraint can often lead to the selection of other data structures, like ArrayList, for more dynamic data requirements.

Internal Memory Management

Arrays in Java consist of:

  • Stack Memory: Stores the reference variable of the array.
  • Heap Memory: Stores the actual array object and its elements.

When you declare an array, the reference is created in the stack memory, and the array object is stored in the heap memory.

Memory Allocation

There are two critical stages in an array's memory allocation:

  1. Declaration: The reference variable is created, but it does not point anywhere.
  2. Initialization: The reference variable points to the actual array object in the heap, which contains the elements.

For example:

int[] rollNumbers; // Declaration
rollNumbers = new int[5]; // Initialization
Copier après la connexion

Dynamic Memory Allocation

Java performs dynamic memory allocation, meaning that at runtime, it allocates memory as required, making it efficient in memory management.

Input and Output in Arrays

Taking Input

To populate an array with user input, you can use a loop along with a Scanner for reading input from the console.

Scanner scanner = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    System.out.print("Enter element " + (i + 1) + ": ");
    arr[i] = scanner.nextInt();
}
Copier après la connexion

Printing Arrays

You can print arrays using loops or the Arrays.toString() utility method for more readable output.

for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
}
Copier après la connexion

or

System.out.println(Arrays.toString(arr));
Copier après la connexion

Multi-Dimensional Arrays

Two-dimensional arrays, or matrices, are arrays of arrays. The syntax for a 2D array looks like this:

int[][] matrix = new int[3][3];
Copier après la connexion

Example

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
Copier après la connexion

For a dynamic input of elements into a 2D array, nested loops are used.

ArrayList: A Dynamic Alternative

Arrays in Java are of fixed size, leading to inefficiencies when the number of elements is unknown at compile time. This limitation can be overcome by using the ArrayList class, part of the Java Collections Framework.

Using ArrayList

The ArrayList class provides dynamic resizing. Here’s the syntax for creating an ArrayList:

ArrayList<Integer> numbers = new ArrayList<>();
Copier après la connexion

You can add and manipulate elements dynamically:

numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println(numbers); // Output: [1, 2, 3]

numbers.set(1, 10); // Change element at index 1
System.out.println(numbers); // Output: [1, 10, 3]

numbers.remove(0); // Remove element at index 0
System.out.println(numbers); // Output: [10, 3]

boolean contains = numbers.contains(10); // Check if the list contains 10
System.out.println(contains); // Output: true
Copier après la connexion

Internal Working of ArrayList

Internally, ArrayList uses dynamic arrays with an initial fixed capacity. When this capacity is exhausted, a new array with greater capacity is created, and existing elements are copied over. This process ensures that the ArrayList can grow dynamically as elements are added.

Common Array Operations

Finding Maximum Elements

To find the maximum element in an array, iterate through the array and keep track of the highest value:

int max = arr[0];
for (int i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}
System.out.println("Maximum value: " + max);
Copier après la connexion

Reversing an Array

To reverse an array, use a two-pointer technique:

public static void reverse(int[] arr) {
    int start = 0;
    int end = arr.length - 1;
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
Copier après la connexion

Calling the reverse function:

int[] arr = {1, 2, 3, 4, 5};
reverse(arr);
System.out.println(Arrays.toString(arr)); // Output: [5, 4, 3, 2, 1]
Copier après la connexion

Conclusion

Arrays are a critical data structure in Java, enabling the storage and manipulation of data sets efficiently. While fixed in size, arrays are powerful and versatile when dealing with homogeneous data types. For dynamic data needs, ArrayList provides additional flexibility, allowing arbitrary growth in size. Understanding these structures and their operations lays the groundwork for more advanced programming and data management. Moreover, practicing array operations and understanding their underlying memory management helps in writing more efficient and optimized code.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal