从 ArrayList 中检索随机项 [重复]

Posted

技术标签:

【中文标题】从 ArrayList 中检索随机项 [重复]【英文标题】:Retrieving a random item from ArrayList [duplicate] 【发布时间】:2011-06-29 09:28:15 【问题描述】:

我正在学习 Java,但在使用 ArrayListRandom 时遇到问题。

我有一个名为 catalogue 的对象,它有一个从另一个名为 item 的类创建的对象数组列表。

我需要catalogue 中的一个方法,它返回列表中itemobjects 之一的所有信息。item需要随机选择。

import java.util.ArrayList;
import java.util.Random;

public class Catalogue

    private Random randomGenerator = new Random();
    private ArrayList<Item> catalogue;

    public Catalogue ()
    
        catalogue = new ArrayList<Item>();  
    

    public Item anyItem()
    
        int index = randomGenerator.nextInt(catalogue.size());
        System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
        return catalogue.get(index);
    

当我尝试编译时,我收到一个指向 System.out.println 行的错误说..

'找不到符号变量anyItem'

【问题讨论】:

在 SOP 中不仅 anyItem 没有意义,而且您在该行之上还有一个 return。 呵呵,骗人的,不是“经理人选”,是随机选的:S 大声笑,为什么这么多赞成票? 【参考方案1】:

anyItem 是一个方法,System.out.println 调用在您的 return 语句之后,因此无论如何都不会编译,因为它无法访问。

可能想像这样重写它:

import java.util.ArrayList;
import java.util.Random;

public class Catalogue

    private Random randomGenerator;
    private ArrayList<Item> catalogue;

    public Catalogue()
     
        catalogue = new ArrayList<Item>();
        randomGenerator = new Random();
    

    public Item anyItem()
    
        int index = randomGenerator.nextInt(catalogue.size());
        Item item = catalogue.get(index);
        System.out.println("Managers choice this week" + item + "our recommendation to you");
        return item;
    

【讨论】:

@Will randomGenerator 为空。您需要在构造函数中创建它。我将更新代码示例。 对于那些来这里寻找更简洁答案的人:Object randomItem = list.get(new Random().nextInt(list.size())) 如果您使用 Java 7,list.get(ThreadLocalRandom.current().nextInt(list.size())) public T getRandom(ArrayList list) return list.get(random.nextInt(list.size())); 【参考方案2】:

您的印刷品是在您返回之后出现的——您永远无法达到那个声明。此外,您从未将 anyItem 声明为变量。你可能想要

public Item anyItem()
    
        int index = randomGenerator.nextInt(catalogue.size());
        Item randomItem = catalogue.get(index);
        System.out.println("Managers choice this week" + randomItem.toString() + "our recommendation to you");
        return randomItem;
    

toString 部分只是一个快速的部分——您可能想要添加一个方法“getItemDescription”,它为此目的返回一个有用的字符串...

【讨论】:

你好,这个选项在这一行抛出一个空指针 int index = randomGenerator.nextInt(catalogue.size());当我尝试调用该方法时。 @will,你从来没有初始化过randomGenerator。在您的目录构造函数中执行此操作。 你说得对,我确实忘记了,Doh!【参考方案3】:

您必须从return 下方删除system.out.println 消息,如下所示:

public Item anyItem()

    randomGenerator = new Random();
    int index = randomGenerator.nextInt(catalogue.size());
    Item it = catalogue.get(index);
    System.out.println("Managers choice this week" + it + "our recommendation to you");
    return it;

return 语句基本上说函数现在将结束。 return 语句之外包含的任何内容都在它的范围内,这将导致您遇到的行为

【讨论】:

拥有it.toString() 和只有it 之间的唯一区别是前者可以抛出NullPointerException 而后者不会。如果it 在变量中,为什么不返回呢? 好点。我会改变答案 你好,这个不行。它为行 int index = randomGenerator.nextInt(catalogue.size()); 提供了一个空指针;【参考方案4】:

试试这个

    public Item anyItem()
    
        int index = randomGenerator.nextInt(catalogue.size());
        System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
        return catalogue.get(index);
    

我强烈建议你买一本书,比如 Ivor Horton 的 Java 入门 2

【讨论】:

【参考方案5】:

anyItem 从未被声明为变量,因此它会导致错误是有道理的。但更重要的是,您在 return 语句之后有代码,这将导致无法访问的代码错误。

【讨论】:

你好。如何声明 anyItem 变量? 你不想,不在那个方法里面。上面有更好的建议。 您好,以上所有建议都为行 int index = randomGenerator.nextInt(catalogue.size()); 提供了一个空指针; 他们给出了空指针,因为我忘了添加 randomGenerator = new Random();在构造函数中。哇! 那么 randomGenerator 或 catalog 为空。使用几个 println 语句检查它们以查看它们是否在此行上方为空。您是否在初始化这两个对象中的任何一个之前调用此代码?编辑:没关系——我刚刚看到你的回复。【参考方案6】:

System.out.println("本周经理的选择" + anyItem + "我们给你的推荐");

您还没有初始化甚至声明变量 anyItem。

这段代码: + 任何项目 +

表示获取Object anyItem的toString方法的值

为什么这不起作用的第二件事。您在 return 语句后有 System.out.print 。程序永远无法到达这条线。

你可能想要这样的东西:

public Item anyItem() 
    int index = randomGenerator.nextInt(catalogue.size());
    System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
    return catalogue.get(index);

顺便说一句:在 Java 中,将大括号放在与函数声明相同的行上。

【讨论】:

你好。我已将 system.out.println 移至返回之前。但是当我尝试调用该方法时,我仍然收到 NullPointer 错误。它指向这一行 int index = randomGenerator.nextInt(catalogue.size()); 你必须先初始化随机数。最适合您的 pklace 在构造函数中。在没有初始化的情况下,变量包含 null,这意味着“这里应该是 Random 类型的变量”。没有它,你要求空的内存空间给你 nextInt。因此 nullpointerException【参考方案7】:

解决方案并不好,即使您修复了该打印输出的命名和无法访问的声明。

你也应该注意的事情 1. 随机性种子和大数据,将 num 的 item 如此大,返回随机

    你没有处理多线程,你可能会得到 index out of bound 异常

【讨论】:

谁说它必须是线程安全的?最好假设不是。您甚至可能处于一个几乎禁止自己处理并发的环境中(EJB,...)。【参考方案8】:

我可以看到代码 System.out.println("Managers choice this week" + anyItem + "our recommendation to you"); 无法访问。

【讨论】:

他编写代码的方式也会导致 *** 错误(使用 AnyItem ==> AnyItem())【参考方案9】:
public static Item getRandomChestItem(List<Item> items) 
    return items.get(new Random().nextInt(items.size()));

【讨论】:

这里究竟被抓到了什么?您应该检查列表是否为空或为空,而不是使用 try catch【参考方案10】:

给你,使用Generics:

private <T> T getRandomItem(List<T> list)

    Random random = new Random();
    int listSize = list.size();
    int randomIndex = random.nextInt(listSize);
    return list.get(randomIndex);

【讨论】:

【参考方案11】:

见https://gist.github.com/nathanosoares/6234e9b06608595e018ca56c7b3d5a57

public static void main(String[] args) 
    RandomList<String> set = new RandomList<>();

    set.add("a", 10);
    set.add("b", 10);
    set.add("c", 30);
    set.add("d", 300);

    set.forEach((t) -> 
        System.out.println(t.getChance());
    );

    HashMap<String, Integer> count = new HashMap<>();
    IntStream.range(0, 100).forEach((value) -> 
        String str = set.raffle();
        count.put(str, count.getOrDefault(str, 0) + 1);
    );

    count.entrySet().stream().forEach(entry -> 
        System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));
    );

输出:

2.857142857142857

2.857142857142857

8.571428571428571

85.71428571428571

一:2

b: 1

c: 9

d: 88

【讨论】:

【参考方案12】:

这是一种更好的处理方式:

import java.util.ArrayList;
import java.util.Random;

public class facultyquotes

    private ArrayList<String> quotes;
    private String quote1;
    private String quote2;
    private String quote3;
    private String quote4;
    private String quote5;
    private String quote6;
    private String quote7;
    private String quote8;
    private String quote9;
    private String quote10;
    private String quote11;
    private String quote12;
    private String quote13;
    private String quote14;
    private String quote15;
    private String quote16;
    private String quote17;
    private String quote18;
    private String quote19;
    private String quote20;
    private String quote21;
    private String quote22;
    private String quote23;
    private String quote24;
    private String quote25;
    private String quote26;
    private String quote27;
    private String quote28;
    private String quote29;
    private String quote30;
    private int n;
    Random random;

    String teacher;


    facultyquotes()
    
        quotes=new ArrayList<>();
        random=new Random();
        n=random.nextInt(3) + 0;
        quote1="life is hard";
        quote2="trouble shall come to an end";
        quote3="never give lose and never get lose";
        quote4="gamble with the devil and win";
        quote5="If you don’t build your dream, someone else will hire you to help them build theirs.";
        quote6="The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself.";
        quote7="When I dare to be powerful – to use my strength in the service of my vision, then it becomes less and less important whether I am afraid.";
        quote8="Whenever you find yourself on the side of the majority, it is time to pause and reflect";
        quote9="Great minds discuss ideas; average minds discuss events; small minds discuss people.";
        quote10="I have not failed. I’ve just found 10,000 ways that won’t work.";
        quote11="If you don’t value your time, neither will others. Stop giving away your time and talents. Value what you know & start charging for it.";
        quote12="A successful man is one who can lay a firm foundation with the bricks others have thrown at him.";
        quote13="No one can make you feel inferior without your consent.";
        quote14="Let him who would enjoy a good future waste none of his present.";
        quote15="Live as if you were to die tomorrow. Learn as if you were to live forever.";
        quote16="Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do.";
        quote17="The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will.";
        quote18="Success is about creating benefit for all and enjoying the process. If you focus on this & adopt this definition, success is yours.";
        quote19="I used to want the words ‘She tried’ on my tombstone. Now I want ‘She did it.";
        quote20="It is our choices, that show what we truly are, far more than our abilities.";
        quote21="You have to learn the rules of the game. And then you have to play better than anyone else.";
        quote22="The successful warrior is the average man, with laser-like focus.";
        quote23="Develop success from failures. Discouragement and failure are two of the surest stepping stones to success.";
        quote24="If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much.";
        quote25="The question isn’t who is going to let me; it’s who is going to stop me.";
        quote26="If you genuinely want something, don’t wait for it – teach yourself to be impatient.";
        quote27="Don’t let the fear of losing be greater than the excitement of winning.";
        quote28="But man is not made for defeat. A man can be destroyed but not defeated.";
        quote29="There is nothing permanent except change.";
        quote30="You cannot shake hands with a clenched fist.";

        quotes.add(quote1);
        quotes.add(quote2);
        quotes.add(quote3);
        quotes.add(quote4);
        quotes.add(quote5);
        quotes.add(quote6);
        quotes.add(quote7);
        quotes.add(quote8);
        quotes.add(quote9);
        quotes.add(quote10);
        quotes.add(quote11);
        quotes.add(quote12);
        quotes.add(quote13);
        quotes.add(quote14);
        quotes.add(quote15);
        quotes.add(quote16);
        quotes.add(quote17);
        quotes.add(quote18);
        quotes.add(quote19);
        quotes.add(quote20);
        quotes.add(quote21);
        quotes.add(quote22);
        quotes.add(quote23);
        quotes.add(quote24);
        quotes.add(quote25);
        quotes.add(quote26);
        quotes.add(quote27);
        quotes.add(quote28);
        quotes.add(quote29);
        quotes.add(quote30);
    

    public void setTeacherandQuote(String teacher)
    
        this.teacher=teacher;
    

    public void printRandomQuotes()
    
        System.out.println(quotes.get(n++)+"  ~ "+ teacher);  
    

    public void printAllQuotes()
    
        for (String i : quotes)
        
            System.out.println(i.toString());
        
    

【讨论】:

请不要使用编号变量。另外,我们真的不需要看到超过 3 个就能明白这一点

以上是关于从 ArrayList 中检索随机项 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从 ArrayList 的 ArrayList 中删除重复项 [重复]

从 ArrayList 中捕获重复项

从ArrayLists的ArrayList中删除重复项[重复]

从 MS Access 检索随机记录的查询 [重复]

使用循环从字符数组列表中删除重复项? [复制]

在重复函数中检索 ArrayList 的值