Shuffle ArrayList对象

时间:2017-06-09 05:57:06

标签: java android

在标记重复或下注之前仔细阅读。

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

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

我的DummyData类有三个String字段。

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吗?

2 个答案:

答案 0 :(得分:5)

嗨Sumit我不知道为什么几乎没有downvote是因为你没有告知你是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);
    }
}

答案 1 :(得分:-1)

试试这个

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());