Cómo mover un elemento específico en la lista de matrices al primer elemento


Por ejemplo: Una lista

A B C D E

Dado C, Cambiar a

C A B D E

Observe que el tamaño de la matriz cambiará, algunos elementos pueden eliminarse en tiempos de ejecución

Collections.swap(url, url.indexOf(itemToMove), 0);

Esta declaración no está funcionando porque la salida C B A D E no C A B D E , cómo arreglarlo?

Gracias.

Author: user782104, 2013-11-25

6 answers

Lo que quieres es una operación muy cara en un ArrayList. Requiere cambiar cada elemento entre el principio de la lista y la ubicación de C por uno.

Sin embargo, si realmente quieres hacerlo:

int index = url.indexOf(itemToMove);
url.remove(index);
url.add(0, itemToMove);

Si esta es una operación frecuente para usted, y el acceso aleatorio es bastante menos frecuente, puede considerar cambiar a otra implementación List como LinkedList. También debe considerar si una lista es la estructura de datos correcta si está tan preocupado sobre el orden de los elementos.

 69
Author: Chris Hayes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-14 12:11:11

Use esto : Eliminar: ArraylistObj.remove(object); Añadir en una posición específica: ArrayListObj.add(position, Object);

Según su código use esto:

url.remove("C");
url.add(0,"C");
 10
Author: Venkata Krishna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-25 07:19:34

El problema es, se intercambia C con A, por lo que A B C D E se convierte en C B A D E.

Podrías intentar algo como esto:

url.remove(itemToMove);
url.add(0, itemToMove);

O si url es un LinkedList:

url.remove(itemToMove);
url.addFirst(itemToMove);
 4
Author: hbsrud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-25 08:22:12

Otra solución, simplemente sigue cambiando de 0 a indexOf(itemToMove).

Esta es mi versión Kotlin:

val list = mutableListOf('A', 'B', 'C', 'D', 'E')
(0..list.indexOf('C')).forEach {
    Collections.swap(list, 0, it)
}

Lo siento, no estoy familiarizado con Java, pero aprendí un poco de Kotlin. Pero el algoritmo es el mismo.

 1
Author: MYLS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-05 13:06:31

Este código le permitirá aumentar el tamaño de la lista, e insertar elementos sin perturbar el orden de la lista

private void insert(double price){
    for(int i = 0; i < keys.size(); i++){
        if(price > keys.get(i)){
            keys.add(null);
            for(int j = keys.size()-1; j > i; j--){
                Collections.swap(keys, j, j-1);
            }
            keys.add(price);
            Collections.swap(keys, keys.size()-1, i);
            keys.remove(keys.size()-1);
            return;
        }
    }
    keys.add(price);
}
 0
Author: sbc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-27 02:08:11

Digamos que tienes una matriz:

String[] arrayOne = new String[]{"A","B","C","D","E"};

Ahora desea colocar el C, en el index 0 obtener el C en otra variable

String characterC = arrayOne[2];

Ahora ejecute el bucle como sigue:

for (int i = (2 - 1); i >= 0; i--) {

            arrayOne[i+1] = arrayOne[i];
        }

Por encima de 2 es el índice de C. Ahora insértese C en el índice, por ejemplo, en 0

arrayOne[0] = characterC;

El resultado del bucle anterior será así:

arrayOne: {"C","A","B","D","E"}

Al final, alcanzamos nuestra meta.

 0
Author: Zulqarnain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-21 11:52:56