出现多个0是因为初始化int[]数组时默认值就是0
你这个问题无非是想找出一个数组中出现频率高的数,那么光靠排序是不行的。你需要遍历数组,使用一个map将数字与出现的次数保留起来。然后排序。
public class RunTest {
public static void main(String[] args) {
int[] a= {1,5,4,3,56,47,21,3,6,9,0,0,1,1,1};
Set
Map
//使用set存放出现的所有字母
for(int aa:a){
uniqChar.add(aa);
}
//使用map记录每个字母在多少个字符串中出现
for(int s:uniqChar){
int times = 0;
for(int aa:a){
if(aa == s){
times++;
}
}
timeMap.put(s, times);
}
//value 排序map
Map map = sortByValue(timeMap);
//输出频率排序,由高到低
System.out.println(map);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map sortByValue(Map map) {
List list=new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable)((Map.Entry)(o2)).getValue()).compareTo(((Map.Entry)(o1)).getValue());
}
});
Map result=new LinkedHashMap();
for(Iterator it=list.iterator(); it.hasNext();) {
Map.Entry entry=(Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
this.count = new int[多少个];