本文介绍了键值(整数,字符串)清单的最佳结构被混洗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中实现一个键值列表(类型为Integer-String)的结构,并且我想对它进行洗牌。



基本上,我想要做这样的事情。

  code>,然后将多个 Pair对对象添加到列表中,该列表将被混洗。

  public class Pair {
private Integer integer;

私人字串;

//访问者
}

然后:

 列表< Pair> list = new ArrayList< Pair>(); 
//...将一些Pair对象添加到列表
Collections.shuffle(list);


I need to implement a structure in Java that is a key-value list (of types Integer-String) and I want to shuffle it.

Basically, I would like to do something like that.

    public LinkedHashMap<Integer, String> getQuestionOptionsMap(){

    LinkedHashMap<Integer, String>  shuffle = new LinkedHashMap<Integer, String> ();

    if (answer1 != null)
        shuffle.put(new Integer(1), answer1);
    if (answer2 != null)
        shuffle.put(new Integer(2), answer2);
    if (answer3 != null)
        shuffle.put(new Integer(3), answer3);
    if (answer4 != null)
        shuffle.put(new Integer(4), answer4);

    Collections.shuffle(shuffle);
    return shuffle;
}

However, HashMap cannot be shuffled.

I could randomly get a key from the hashmap, and then return the linked element, but I'm sure this is not the best solution for my problem.

Is there any better way?

Thanks in advance.

解决方案

Create a Pair class, that holds both the Integer and the String and then add multiple Pair objects to a List, which will be shuffled.

public class Pair {
  private Integer integer;

  private String string;

  //accessors
}

Then:

List<Pair> list = new ArrayList<Pair>();
//...add some Pair objects to the list
Collections.shuffle(list);

这篇关于键值(整数,字符串)清单的最佳结构被混洗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 10:46