Array without repetition

Asked

Viewed 894 times

3

How to do not repeat data at each run?

Each time I Run, he ends up repeating the dates at the time of execution, as I do for Him to draw the dates without repeating them, and when he finishes the number of dates available on this Collection he displays a message that the options are over?

package DeclaracaoArray;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Declaracao_Array {

    public static void main(String[] args) {
        Declaracao_Array d = new Declaracao_Array();
        System.out.println(d.data());
    }

    public String data (){
        List<String> lista = new ArrayList<String>();


        lista.add ( "01/09/2015" );
        lista.add ( "02/09/2015" );
        lista.add ( "03/09/2015");
        lista.add ( "04/09/2015");
        lista.add ( "08/09/2015" );
        lista.add ( "09/09/2015" );
        lista.add ( "10/09/2015");
        lista.add ( "11/09/2015");
        lista.add ( "14/09/2015" );
        lista.add ( "15/09/2015" );
        lista.add ( "17/09/2015");
        lista.add ( "18/09/2015");
        lista.add ( "21/09/2015" );
        lista.add ( "22/09/2015" );
        lista.add ( "23/09/2015");


        Collections.shuffle ( lista );


        return lista.get(0);

    }

}
  • What do you mean não repetir os dados a cada execução?

  • Do not repeat data from a new list ?

  • I’ll edit the question, it’s vague... I’m sorry.

  • The shuffle() is not shuffling?

  • @jsantos1991 worked, put as a response I will vote for her.

1 answer

3


If you want there to be no repetitions, before returning the value remove from the list:

package DeclaracaoArray;

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Declaracao_Array {

    public static void main(String[] args) {
        Declaracao_Array d = new Declaracao_Array();
        System.out.println(d.data());
    }

    public String data (){
        List<String> lista = new ArrayList<String>();


        lista.add ( "01/09/2015" );
        lista.add ( "02/09/2015" );
        //...
        lista.add ( "23/09/2015");

        //verifique se já não está vazia
        if(lista.isEmpty()) return "Opções esgotadas.";
        else{
            Collections.shuffle ( lista );
            String aux = lista.get(0);
            lista.remove(0);
            return aux;
        }    
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.