我创建了一个ArrayList<MyObjects>
。 MyObject
有一个属性priority
,并实现了我已重写的类似方法。
我想要:
排序ArrayList<MyObjects>
基于priority
属性。我已经这样做了:
Collections.sort(ArrayList<MyObjects>)
但是,排序后,我想(仅)随机洗牌具有相同 priority
的元素,保持优先级的一般顺序。
示例:
ArrayList <myObject> objectList = new ArrayList <MyObject>();
objectList = {object1, object2, object3, object4,
object5, object6, object7, object8, object9}
Collections.sort(objectList)
myObject 有一个 compareTo()
比较 priority
的方法两个 myObject。
假设排序后,对象的顺序为:
object7
object8
object4
object5
object1 // priority = 2
object2 // priority = 2
object3 // priority = 2
object9
object8
object1
, object2
,和object3
都具有相同的优先级。
如何在不影响其他对象的情况下对它们进行洗牌?
也就是说,有一个列表:
object7
object8
object4
object5
objectx // priority = 2
objecty // priority = 2
objectz // priority = 2
// where {x, y, z} are randomly selected from {1, 2, 3}
object9
object8
我想在 compareTo()
中进行随机分配方法,当它具有相等性时。
@Override
public int compareTo(MyObject otherObject) {
int comparison;
if (this.priority < otherObject.priority) {comparison = +1;}
else if (this.priority > otherObject.priority) {comparison = -1;}
else {
Random generator = new Random();
comparison = generator.nextInt( 3 ) - 1;
}
return comparison;
但我想当我调用Collections.sort(ArrayList<MyObjects>)
时随机性将不成立。
我应该创建自己的排序算法吗?
或者洗牌算法?
或者是否已经存在一种算法可以对列表中的一组特定元素进行打乱?
最佳答案
在对列表进行排序之前,将其打乱。 Collections.sort
保证是稳定的排序,因此相等的元素将与它们在未排序的集合中的顺序相同...您只需要确保该顺序是适当的随机顺序一。 Collections.shuffle
是最简单的方法:
Collections.shuffle(objectList);
Collections.sort(objectList);
关于java - 如何随机排列列表中的特定元素集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37634260/