【问题标题】:Shuffle ArrayList of objects [duplicate]随机播放对象的ArrayList [重复]
【发布时间】:2017-11-11 00:39:50
【问题描述】:

在标记重复或否决之前仔细阅读。

我的要求是洗牌对象的 Arraylist 保持列表数据相同只是改变位置。 我有一个 Dummydata 类型:

List<DummyData> dataList = new ArrayList<>();

我的 DummyData 类有三个字符串字段。

So adding some data for clarification:

dataList.add(new DummyData("Item1","Price1","Discount1"));
dataList.add(new DummyData("Item2","Price2","Discount2"));
dataList.add(new DummyData("Item3","Price3","Discount3"));
dataList.add(new DummyData("Item4","Price4","Discount4"));
dataList.add(new DummyData("Item5","Price5","Discount5"));

当我使用 Collections.shuffle(dataList);

输出是:

Item5 Price3 Discount4
Item2 Price1 Discount2
and some random output like this everytime.

我的预期输出是:

Item2 Price2 Discount2
Item5 Price5 Discount5
Item1 Price1 Discount1

只是位置应该改变列表数据不应该混乱。 所以我的问题是否可以使用 Collections.shuffle 来实现?

【问题讨论】:

  • 什么是dataList?它不能是 java.util.ArrayList,因为它没有接受 3 个参数的 add 方法。
  • 将这三个项目分别封装在一个容器中。然后打乱这些容器的列表。
  • Eran 完全正确,您的代码无法按照您描述的那样运行,因此您没有描述您的实际问题,因此没有水晶球没有人可以帮助您。
  • 在标记重复或否决之前仔细阅读。相同的结果
  • 老实说,以 在标记重复或否决之前仔细阅读。 如果不这样做,会惹恼很多人不仔细发帖。第一条评论突出了您的代码的问题,您似乎忽略了它并继续进攻。没什么好说的了。

标签: java android


【解决方案1】:

嗨,Sumit,我不知道为什么很少有人投反对票,这是因为您还没有告知您是 Java 语言的新手 请在下面找到我的答案

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

final class Product {
    private final String name;
    private final Double price;
    private final Double discount;

    Product(String name, Double price, Double discount) {
        this.name = name;
        this.price = price;
        this.discount = discount;
    }

    @Override
    public String toString() {
        return "{name=" + name + ", price=" + price + ", discount=" + discount + "}";
    }
}

public final class Main {

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Watch", 45.99, 9.99));
        products.add(new Product("Keyboard", 21.99, 3.99));
        products.add(new Product("Mouse", 99.99, 4.99));

        System.out.println("Original items Before shuffle are");
        products.forEach(System.out::println);

        Collections.shuffle(products);
        System.out.println("Original items After shuffle are");
        products.forEach(System.out::println);
    }
}

【讨论】:

  • 非常感谢@sector11 我的代码问题是我使用的是 ArrayList 而不是 LinkedList。
  • 当我提供了回答问题所需的所有必要信息时,不知道他们为什么投了反对票。
  • @sumit 为 ArrayList 更新,是的,他们有权否决您的问题还不是很清楚!!
  • 他们拥有我知道的权利,但在哪些方面我的问题尚不清楚
  • 你不清楚你的方法,无论如何让我们同意你有一个解决方案可以恢复工作!!!
【解决方案2】:

试试这个

Collections.shuffle(dataList);
Log.d(TAG,dataList.toString());

用你的逻辑工作

   Collections.shuffle(dataList);
    ArrayList<DummyData> l1=new ArrayList<>();
    for(DummyData e : dataList){
        l1.add(e);
    }
    Log.d(TAG,l1.toString());

【讨论】:

  • 你知道l1.toString()的输出吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2015-11-19
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多