我只想获取一个公司名称,并且只想获取一次。因此,如果已经获取了它,则不应再次获取它。

这是代码:

private static String[] billercompanies = {
    "1st",
    "TELUS Communications",
    "Rogers Cablesystems",
    "Shaw Cable",
    "TELUS Mobility Inc",
    "Nanaimo Regional District of",
    "Credit Union MasterCard",
    };



public static String GetBillerCompany(){
    String randomBillerComp = "";
    randomBillerComp = (billercompanies[new Random().nextInt(billercompanies.length)]);
    return randomBillerComp;
}

最佳答案

在列表中创建副本,并在已获取元素时将其删除。

Arrays.asList(array)不可修改,但您可以将其包装在功能齐全的列表中。

List<String> billercompaniesList = new ArrayList<>(Arrays.asList(billercompanies));

String randomBillerComp = "";

Random random = new Random();
// first retrieval
int index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);


// second retrieval
index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);

// and so for

09-05 08:34