我需要在Java中实现一个键值列表(类型为Integer-String)的结构,我想要将其改组。
基本上,我想做那样的事情。
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;
}
但是,HashMap无法改组。
我可以从hashmap中随机获取一个键,然后返回链接元素,但我确信这不是我问题的最佳解决方案。
还有更好的方法吗?
提前致谢。
答案 0 :(得分:11)
创建一个Pair
类,同时包含Integer
和String
,然后将多个Pair
对象添加到List中,这些对象将被随机播放。
public class Pair {
private Integer integer;
private String string;
//accessors
}
然后:
List<Pair> list = new ArrayList<Pair>();
//...add some Pair objects to the list
Collections.shuffle(list);
答案 1 :(得分:8)
您可以保留地图。地图设计为按键查找,所以我建议你有一个随机密钥列表。
public Map<Integer, String> getQuestionOptionsMap() {
Map<Integer, String> map = new HashMap<>();
String[] answers = {null, answer1, answer2, answer3, answer4};
for (int i = 1; i < answers.length; i++)
if (answers[i] != null)
map.put(i, answers[i]);
List<Integer> order = new ArrayList<>(map.keySet());
Collections.shuffle(order);
Map<Integer, String> shuffled = new LinkedHashMap<>();
for (Integer key : order)
shuffled.put(key, map.get(key));
return shuffled;
}
答案 2 :(得分:2)
您可以保留单独的List
个键值,将其随机播放并使用它来访问HashMap
。
List<Integer> keys = new ArrayList<Integer>(map.keySet());
Collections.shuffle(keys);
for(Integer i : keys)
map.get(i); // Gets the values in the shuffled order
答案 3 :(得分:0)
Hashtable<Integer, String>
替代不太方便和有效的List<SomePairClass<Integer, String>>
答案 4 :(得分:0)
例如,您可以使用enum
来实现
package device.packet.data;
public enum TLVList {
SpeedingAlarm(0x1001, 3, Short.class),
LowVoltageAlarm(0x1002, 3, Short.class),
OBDCommunicationError(0x1015, 3, Short.class),
IgnitionOn(0x1016, 3, Short.class),
IgnitionOff(0x1017, 3, Short.class),
MILAlarm(0x1018, 3, Short.class),
UnlockAlarm(0x1019, 3, Short.class),
NoCardPresented(0x101A, 3, Short.class),
HiddenCommand(0x101B, 3, Short.class),
Vibration(0x101C, 3, Short.class),
DoorOpened(0x101D, 3, Short.class);
private int tagFlagHex;
private int length;
private Class aClass;
public int gettagFlagHex() {
return tagFlagHex;
}
public int getLength() {
return length;
}
public Class getClassType() {
return aClass;
}
TLVList(int tagFlagHex, int length, Class aClass) {
this.tagFlagHex = tagFlagHex;
this.length = length;
this.aClass = aClass;
}
public static TLVList of(Integer tagFlagHex) {
for (TLVList tagFlag : TLVList.values()) {
if(tagFlag.tagFlagHex == tagFlagHex) return tagFlag;
}
return null;
}
}
我希望这会有所帮助。