To tell you simply it doesn’t work, please use variable increment operation Then if each element of yours is unique and you are traversing List, then indexOf can be used, but there is a problem that the performance is not as good as yours Use the variable increment operation yourself Also, if the subscript is very important to you, then why not use the traditional for statement
I just tried it. Linkedlist traversal in the traditional way is very slow, but foreach is very fast, even with a custom auto-increment variable added. It is even said to be faster than traditional loop traversal of linear tables.
public void testArrayList() {
List<String> outList = new ArrayList<>(1000000);
Date date = new Date();
for(int i = 0; i < 1000000; i++) {
outList.add(String.valueOf(i + 1));
}
Date date1 = new Date();
System.out.println("构建对象用时:" + (date1.getTime() - date.getTime()));
StringBuilder sb = new StringBuilder();
Calendar cal = Calendar.getInstance();
for(int i = 0; i < outList.size(); i++) {
sb.append(outList.get(i));
}
Calendar cal1 = Calendar.getInstance();
long time = cal1.getTimeInMillis() - cal.getTimeInMillis();
System.out.println(time);
}
public void testLinkedList() {
List<String> outList = new LinkedList<>();
Date date = new Date();
for(int i = 0; i < 1000000; i++) {
outList.add(String.valueOf(i + 1));
}
Date date1 = new Date();
System.out.println("构建对象用时:" + (date1.getTime() - date.getTime()));
StringBuilder sb = new StringBuilder();
Calendar cal = Calendar.getInstance();
for(String num : outList) {
sb.append(num);
}
Calendar cal1 = Calendar.getInstance();
long time = cal1.getTimeInMillis() - cal.getTimeInMillis();
System.out.println(time);
}
You can compare the object creation time and traversal time of linear lists and linked lists by yourself.
To tell you simply it doesn’t work, please use variable increment operation
Then if each element of yours is unique and you are traversing List, then indexOf can be used, but there is a problem that the performance is not as good as yours Use the variable increment operation yourself
Also, if the subscript is very important to you, then why not use the traditional for statement
I just tried it. Linkedlist traversal in the traditional way is very slow, but foreach is very fast, even with a custom auto-increment variable added. It is even said to be faster than traditional loop traversal of linear tables.
You can compare the object creation time and traversal time of linear lists and linked lists by yourself.