情景:配置的实现是:Map,然后插入sn,然后将values()转为List让程序使用,由于sn都是整形的,那么findAll()是有序的吗?
例子1:测试下
package org.example.TestSet;import com.google.common.collect.Lists;
import com.google.common.collect.Maps;import java.util.List;
import java.util.Map;public class Main {public static class A implements Comparable {private int val;public A(int val) {this.val = val;}public int getVal() {return val;}@Overridepublic int compareTo(A o) {return val - o.val;}@Overridepublic String toString() {return "A{" +"val=" + val +'}';}}public static void main(String[] args) {// 有序,根据key排序Map treeMap = Maps.newTreeMap();// 无序!!!
// Map treeMap = Maps.newHashMap();for (int i = 1; i < Integer.MAX_VALUE / 1000; i++) {treeMap.put(i, new A(i));}List list = Lists.newArrayList(treeMap.values());for (int i = 0; i < list.size() - 1; i++) {int cur = list.get(i).getVal();int next = list.get(i + 1).getVal();int diff = next - cur;if (diff < 0) {System.out.println("i = " + i + " diff = " + diff + " cur = " + cur + " next = " + next);}}}
}/*
Map的时候:// 第一个是65535
i = 707332 diff = -3 cur = 707343 next = 707340
i = 707334 diff = -11 cur = 707341 next = 707330
i = 707336 diff = -3 cur = 707331 next = 707328
i = 707340 diff = -3 cur = 707335 next = 707332
i = 707344 diff = -3 cur = 707355 next = 707352
i = 707348 diff = -3 cur = 707359 next = 707356
i = 707350 diff = -11 cur = 707357 next = 707346
i = 707352 diff = -3 cur = 707347 next = 707344
i = 707356 diff = -3 cur = 707351 next = 707348TreeMap则是绝对的有序*/
可以看出来:Map在有65535个元素后,顺序就会变化了。
例子2:根据跨服天数查某天的奖励,请使用TreeMap
package org.example.TestSet;import com.google.common.collect.Maps;import java.util.Map;
import java.util.TreeMap;public class Main {public static class Conf implements Comparable {private int val;public Conf(int val) {this.val = val;}public int getVal() {return val;}@Overridepublic int compareTo(Conf o) {return val - o.val;}@Overridepublic String toString() {return "Conf{" +"val=" + val +'}';}}public static void main(String[] args) {TreeMap treeMap = Maps.newTreeMap();treeMap.put(4, new Conf(4));treeMap.put(14, new Conf(14));treeMap.put(8, new Conf(8));treeMap.put(9999, new Conf(9999));treeMap.put(54, new Conf(54));System.out.println(getConf(treeMap, 3));System.out.println(getConf(treeMap, 8));System.out.println(getConf(treeMap, 53));System.out.println(getConf(treeMap, 9999999));}public static Conf getConf(TreeMap treeMap, Integer key) {Map.Entry entry = treeMap.ceilingEntry(key);if (entry != null) {return entry.getValue();}return treeMap.lastEntry().getValue();}
}/*
Conf{val=4}
Conf{val=8}
Conf{val=54}
Conf{val=9999}*/