To shuffle the elements in an ArrayList randomly, you can use the Collections.shuffle() method from the java.util package.
This method randomly permutes the elements in the specified list.
Here's the Java program:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListShuffle {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
System.out.println("Original List: " + numbers);
shuffleArrayList(numbers);
System.out.println("Shuffled List: " + numbers);
}
public static void shuffleArrayList(List<Integer> list) {
Collections.shuffle(list);
}
}
Explanation:
- We define a class called ArrayListShuffle.
- In the main method, we create an ArrayList called numbers containing some integers. You can modify this list with your desired input elements.
- We print the original list using System.out.println.
- We call the shuffleArrayList method to shuffle the elements in the list.
- The shuffleArrayList method takes an ArrayList as input and uses Collections.shuffle() to shuffle its elements randomly.
- Finally, we print the shuffled list using System.out.println.
The output will be different each time you run the program due to the random shuffling. For example:
Original List: [1, 2, 3, 4, 5]
Shuffled List: [3, 5, 1, 2, 4]
Remember that each time you run the program, you'll get a different random permutation of the elements in the list.
0 Comments