代码如下,感觉比用数组做更容易理解
import java.util.*;
public class SearchTest {
public static void main(String[] args) {
int a[] = new int[50];
Random r = new Random();
for(int i = 0;i<50;i++)
{
a[i] = r.nextInt(40)+10;
}
SearchTest st = new SearchTest();
a = st.asort(a);
System.out.println("随机生成50个(10,50)的数,排序为:");
for(int i = 0;i<50;i++)
{
System.out.print(a[i]+",");
}
System.out.println();
System.out.println("统计结果如下:");
System.out.println();
st.searchnum2(a);
}
public int[] asort(int[] a)//冒泡排序
{
int temp;
for(int i = 0;i<a.length-1;i++)
{
for(int j = 0;j<a.length-1;j++)
{
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
public void searchnum2(int[] a) //查找个数(利用map)
{
HashMap map = new HashMap();
for(int i = 0;i<a.length;i++)
{
if(map.get(a[i]) == null) //map的key中没有该元素的话,添加
{
map.put(a[i],new Integer(1));
}
else //map的key中有此元素,数量(Value)+1
{
Integer in = (Integer) map.get(a[i]);
in = new Integer(in.intValue()+1);
map.put(a[i],in); //替换掉旧的元素
}
}
//System.out.println(map);
Set set = map.keySet(); //得到key的集合
Iterator i = set.iterator(); //迭代集合
while(i.hasNext()) //输出map的每个value
{
Integer in = (Integer)i.next();
System.out.println("数字"+in.intValue()+"有"+map.get(in.intValue())+"个");
}
}
}
程序运行结果为
随机生成50个(10,50)的数,排序为:
10,11,11,14,14,15,15,16,16,22,22,23,26,27,27,27,27,28,28,29,29,30,31,31,32,32,32,34,35,35,35,35,36,36,37,38,39,39,41,45,45,45,45,46,46,48,48,48,49,49,
统计结果如下:
数字10有1个
数字11有2个
数字14有2个
数字15有2个
数字16有2个
数字22有2个
数字23有1个
数字26有1个
数字27有4个
数字28有2个
数字29有2个
数字30有1个
数字31有2个
数字32有3个
数字34有1个
数字35有4个
数字36有2个
数字37有1个
数字38有1个
数字39有2个
数字41有1个
数字45有4个
数字46有2个
数字48有3个
数字49有2个
有一种极简写法
public void searchnum3(int[] a)
{
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(Integer in :a)
{
map.put(in,map.get(in)==null?1:map.get(in)+1);
}
System.out.println(map);
}
结果如下
随机生成50个(10,50)的数,排序为:
10,11,11,12,12,13,13,15,16,16,16,16,17,17,18,21,22,23,24,24,24,25,26,26,28,30,30,30,31,31,34,34,35,37,38,39,43,44,44,44,44,45,45,45,46,46,46,47,47,47,
统计结果如下:
{10=1, 11=2, 12=2, 13=2, 15=1, 16=4, 17=2, 18=1, 21=1, 22=1, 23=1, 24=3, 25=1, 26=2, 28=1, 30=3, 31=2, 34=2, 35=1, 37=1, 38=1, 39=1, 43=1, 44=4, 45=3, 46=3, 47=3}