今天看到網上一篇文章說:Set檢索元素效率低下,刪除和插入效率高;List查找元素效率高,插入刪除元素效率低。因而想到List雖然用get(index)方法查詢效率高,可是若用contains方法查詢對象元素,Set集合應該比List效率要高,下面是實驗證實操做過程。html
實體類:java
![](http://static.javashuo.com/static/loading.gif)
準備數據代碼:算法
List<Student> list = new ArrayList<Student>(); Set<Student> set = new HashSet<Student>(); Student s = null; for(int i = 0; i <= 100000; i++){ s = new Student("name"+i,"addr"+i); list.add(s); set.add(s); }
查詢第一個對象:post
代碼:測試
long start = System.currentTimeMillis(); Student stu = new Student("name0","addr0"); System.out.println(list.contains(stu)); // System.out.println(set.contains(stu)); long end = System.currentTimeMillis(); System.out.println("查詢對象 "+stu.toString()+"\n共耗費時間:"+(end-start)+ "毫秒");
使用ArrayList查詢結果結果:;spa
使用HashSet查詢結果:code
查詢第一個對象太簡單了,它們都幾乎不用花時間...htm
查詢靠後的對象:對象
代碼:blog
long start = System.currentTimeMillis(); Student stu = new Student("name100000","addr100000"); // System.out.println(list.contains(stu)); System.out.println(set.contains(stu)); long end = System.currentTimeMillis(); System.out.println("查詢對象 "+stu.toString()+"\n共耗費時間:"+(end-start)+ "毫秒");
使用ArrayList查詢結果結果:;
使用HashSet查詢結果:
HashSet快一些。。。
經過屢次調用contains方法分別查詢開頭到結尾全部對象:
代碼:
long start = System.currentTimeMillis(); for(int i = 0; i<= 100000; i++){ s = new Student("name"+i,"addr"+i); System.out.println(i+"__"+list.contains(s)); // System.out.println(i+"__"+set.contains(s)); } long end = System.currentTimeMillis(); System.out.println("查詢10000個對象 \n共耗費時間:"+(end-start)+ "毫秒");
使用ArrayList查詢結果結果:;使用HashSet查詢結果:
耗時前者是後者的167.46倍(打印代碼中把100000寫成10000了,可是不影響結果)
總結:使用contains方法查詢元素是否存在HashSet要比ArrayList快的多。