2011-08-16 33 views
11

En Java, sé que para barajar una ArrayList, existe el método Collections.shuffle(), sin embargo, esto mezcla toda la lista.¿Cómo puedo barajar un rango específico de una ArrayList?

¿Cómo puedo escribir un método (o, alguien puede escribir y me muestran que?) Como la siguiente:

private ArrayList<AnObject> list; 

/** 
* Shuffles the concents of the array list in the range [start, end], and 
* does not do anything to the other indicies of the list. 
*/ 
public void shuffleArrayListInTheRange(int start, int end) 
+1

En lugar increíble ver cuatro respuestas que dicen casi lo mismo. :) – Malcolm

Respuesta

22

Uso List.subList y Collections.shuffle, así:

Collections.shuffle(list.subList(start, end)); 

(Tenga en cuenta que el segundo índice es subListexclusivo, así que use end+1 si desea incluir el índice end en el orden aleatorio)

Dado que List.subList devuelve una vista de la lista, los cambios realizados (por el método de reproducción aleatoria) a la lista secundaria también afectarán a la lista original.

2
Collections.shuffle(list.subList(start, end+1)); 

Tenga en cuenta el +1, porque el índice final de subList() es exclusivo.

0

Es muy sencillo

public void shuffleArrayListInTheRange(int start, int end) { 
    Collections.shuffle(list.subList(start, end)); 
} 
+0

¡Duh, llegué tarde! :( – adarshr

Cuestiones relacionadas