目录 | |
1. | List add()与addAll() |
2. | map遍历效率比较 |
1.List add()与addAll()
Collection result = new ArrayList();
Collection list = new ArrayList();
result.addAll(list);//把list中每个元素加到result中,result.size()==list.size()
result.add(list);//将list作为一个对象加到result中,result.size()==1
2.map遍历效率比较
下面列出了两种遍历map方法,统计了下运行时间,根据结果显示第二种遍历方法效率更高。
第一种:
public static void m1(){ HashMap<String,String> hashmap = new HashMap<String,String>(); for (int i = 0; i <10000; i++ ) { hashmap.put(String.valueOf(i), "abcdefghigklmnopq"); } long bs = Calendar.getInstance().getTimeInMillis(); Iterator iterator = hashmap.keySet().iterator(); while (iterator.hasNext()) { hashmap.get(iterator.next()); } System.out.println(1); System.out.println(Calendar.getInstance().getTimeInMillis() - bs); }
第二种:
public static void m2(){ HashMap<String,String> hashmap2 = new HashMap<String,String>(); for (int i = 0; i <10000; i++ ) { hashmap2.put(String.valueOf(i), "abcdefghigklmnopq"); } long bs2 = Calendar.getInstance().getTimeInMillis(); Iterator<Entry<String, String>> it = hashmap2.entrySet().iterator(); while (it.hasNext()) { Entry<String,String> entry = it.next(); entry.getValue(); } System.out.println(2); System.out.println(Calendar.getInstance().getTimeInMillis() - bs2); }
运行结果:
public static void main(String[] args) { // TODO Auto-generated method stub m1(); m2(); } 结果: 1 16 2 0