Ruang penulis
← Kembali ke jurnal
Core API

How do I shuffle elements of an array?

package org.kodejava.util; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayShuffle { public static void main(String[] args) { // Initialize the contents of our array String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}; // As the Collections.shuffle() method need a list for the parameter // we convert our array into […]

DWayan · 19 Nov 2006 · 1 menit baca

Artikel oleh Wayan · Sumber: Kode Java ↗

Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayShuffle {
    public static void main(String[] args) {
        // Initialize the contents of our array
        String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};

        // As the Collections.shuffle() method need a list for the parameter
        // we convert our array into List using the Arrays class.
        List<String> list = Arrays.asList(alphabets);

        // Here we just simply used the shuffle method of Collections class
        // to shuffle out defined array.
        Collections.shuffle(list);

        // Run the code again and again, then you'll see how simple we do
        // shuffling
        for (String alpha : list) {
            System.out.print(alpha + " ");
        }
    }
}

An example of the generated results are:

F H E A B I G J D C  
← Jelajahi catatan lainnya