public static void compare() {
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
for(int i=0;i<100000;i++) {
list.add("a"+i);
}
long t1=0L,t2=0L;
t1 = System.currentTimeMillis();
for(String s : list) {
set.add(s);
}
t2 = System.currentTimeMillis();
System.out.println("forEach遍历的时间为:"+(t2-t1)+"mm");
////two
t1 = System.currentTimeMillis();
for(int i=0; i<list.size(); i++) {
String str = list.get(i);
set.add(list.get(i));
}
t2 = System.currentTimeMillis();
System.out.println("size遍历的时间为:"+(t2-t1)+"mm");
////three
t1 = System.currentTimeMillis();
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
String str = iterator.next();
set.add((String)iterator.next());
}
t2 = System.currentTimeMillis();
System.out.println("iterator遍历的时间为:"+(t2-t1)+"mm");
}
forEach遍历的时间为:45mm
size遍历的时间为:14mm
iterator遍历的时间为:7mm