how to replace an element in array in java

h‮ptt‬s://www.lautturi.com
how to replace an element in array in java

To replace an element in an array in Java, you can use the array indexing syntax to access the element that you want to replace, and then assign a new value to it.

Here is an example of how you can replace an element in an array in Java:

int[] numbers = {1, 2, 3, 4, 5};

// Replace the element at index 2 with the value 10
numbers[2] = 10;

// Print the modified array
for (int i : numbers) {
    System.out.print(i + " ");
}

// Output: 1 2 10 4 5

In this example, the element at index 2 in the numbers array is replaced with the value 10. Then, the modified array is printed to the console using a for-each loop.

Note that arrays in Java are fixed-size, so you cannot change the size of an array once it has been created. If you need to insert or remove elements from an array, you can use an ArrayList instead, which is a resizable array implementation in Java.

Here is an example of how you can replace an element in an ArrayList in Java:

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// Replace the element at index 2 with the value 10
numbers.set(2, 10);

// Print the modified list
for (int i : numbers) {
    System.out.print(i + " ");
}

// Output: 1 2 10 4 5

In this example, the element at index 2 in the numbersArrayList is replaced with the value 10 using the set method. Then, the modified ArrayList is printed to the console using a for-each loop.

Created Time:2017-11-01 20:42:59  Author:lautturi