package com.shrimpking.t1;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/11 10:46
*/
public interface Test
{
void test();
}
package com.shrimpking.t1;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/11 10:47
*/
public class Tester
{
public static long runTest(Test t){
long start = System.nanoTime();
t.test();
long end = System.nanoTime();
return end - start;
}
}
package com.shrimpking.t1;
import sun.security.util.AuthResources_it;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/11 10:49
*/
public class TestMap
{
public static <E> void testSuite(Map<Integer,String> map){
long putTime,getTime,iterateTime;
System.out.println("count\tputTime\tgetTime\titerateTime\t");
//向映射中添加1000个元素
putTime = Tester.runTest(new Test()
{
@Override
public void test()
{
for (int i = 0; i < 1000; i++)
{
map.put(i,"string");
}
}
});
//依次访问1000个元素
getTime = Tester.runTest(new Test()
{
@Override
public void test()
{
for (int i = 0; i < 1000; i++)
{
map.get(i);
}
}
});
//
iterateTime = Tester.runTest(new Test()
{
@Override
public void test()
{
Set<Map.Entry<Integer,String>> entries = map.entrySet();
for (Map.Entry<Integer,String> entry : entries){
Integer key = entry.getKey();
String value = entry.getValue();
}
}
});
System.out.printf("%d\t%d\t%d\t%d\n",1000,putTime,getTime,iterateTime);
}
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<>();
TreeMap<Integer,String> tm = new TreeMap<>();
LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
System.out.println("Test HashMap:");
testSuite(hm);
System.out.println("----------------");
System.out.println("Test TreeMap:");
testSuite(tm);
System.out.println("----------------");
System.out.println("Test LinkedHashMap:");
testSuite(lhm);
}
}