数组和随机值 [英] Arrays and random value

查看:43
本文介绍了数组和随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对随机和数组有疑问.我有一个空列表,我想添加 8 个随机值,但我不想某些值相同.为了获得一些随机值,我使用以下代码:

I have a problem with random and arrays. I have a list empty list and I want to add 8 some random values, but I don't want to some values was the same. To get some random value I use this code:

        for (int i = 0; i < 8; i++) {
            round = random.nextInt(31);
            while (temp.get(round).equals(mix)) {
                round = random.nextInt(31);
            }
            mix.add(temp.get(round));
        }

temp 是包含 32 个对象的列表,mix 是我要添加 8 个随机值的列表.但是当我随机一些值时,有时我会得到相同的值.如何获得随机值但不重复?

temp is list with 32 objects and mix is my list where I want to add 8 random values. But when I random some values sometimes I get the same values. How I can get random values but without duplicates?

推荐答案

虽然其他人已经描述了实现新解决方案的方法,但我认为您可以通过更改一行来解决:

While others have described ways to implement a new solution, I think yours can be fixed by changing a single line:

while (temp.get(round).equals(mix))

我猜这个条件应该检查​​ round 位置的 temp 元素是否已经在 mix 中.应该这样做:

I guess the condition is supposed to check whether the element of temp at position round is already in mix. This should do:

while (mix.contains(temp.get(round))

第一行的问题是 equals 被定义为将一个对象与任何其他类型的对象进行比较,从而比较 temp 的元素,这可能是不是集合本身,mix,即.因此,条件始终为假.Collection.contains 是要使用的方法,需要使用mix 之一.(正如其他人也指出的,Set 最适合经常应用 contains 的情况,但对于 8 种情况,根据您的需要,这无关紧要mix 是否为 List 代替).

The problem with the first line is that equals is defined to compare an object to any other kind of object, and thus compares an element of temp, which is probably not a collection itself, to mix, which is. Thus, the condition is always false. Collection.contains is the method to use, and you need to use the one of mix. (As others have also pointed out, a Set is best suited to a case where contains is applied often, but for 8 cases, as you need, it does not matter much whether mix is a List instead).

:顺便说一句:由于排除了 random.nextInt(int) 中的上限,所以您应该只获得 32 大小的 temp 在你的 mix 中,如果你使用 nextInt(32).

[edit]: By the way: since the upper bound in random.nextInt(int) is excluded, you should only ever get the final element of 32-size temp in your mix if you use nextInt(32).

这篇关于数组和随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆