E
E
Elxan Mecidli2021-04-07 10:00:28
Java
Elxan Mecidli, 2021-04-07 10:00:28

How to change array elements?

public static void main(String[] args) {
        int[] arrey = {1, 2, 3, 4, 5};
        int d = arrey.length;
        System.out.println("Original:" + Arrays.toString(arrey));

        for (int index = 0; index < arrey.length; index++) {
            switch (index) {
                case 0:
                    arrey[index] = arrey[d = d - 1];
                    break;
                case 1:
                    arrey[index] = arrey[d = d - 1];
                    break;
                case 2:
                    arrey[index] = arrey[d = d - 1];
                    break;
                case 3:
                    arrey[index] = arrey[d = d - 1];
                    break;
                case 4:
                    arrey[index] = arrey[d = d - 1];


            }
System.out.println(Arrays.toString(arrey));

I wrote the following code, it gives the following result
Original: [1, 2, 3, 4, 5]
[5, 4, 3, 4, 5
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2021-04-07
@Elxan24-03

Good afternoon.
Answer to your question: https://www.baeldung.com/java-invert-array

E
Erik Mironov, 2021-04-07
@Erik_Mironov

Simple solution using Stream API:

public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int[] result = IntStream.rangeClosed(1, array.length)
                .map(i -> array[array.length - i])
                .toArray();
        System.out.println(Arrays.toString(result));
    }

Even simpler using the Collections class, the List interface, and a wrapper over the int primitive:
public static void main(String[] args) {
        Integer[] array = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(array);
        Collections.reverse(list);
        System.out.println(Arrays.toString(list.toArray()));
    }

If you don’t like the previous options, then you can use the classics:
public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        for (int i = 0; i < array.length / 2; i++) {
            int tmp = array[i];
            array[i] = array[array.length - 1 - i];
            array[array.length - 1 - i] = tmp;
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question