java中foreach语句如何获取数组下标
PHPz
PHPz 2017-04-17 15:54:56
0
2
865

除了在foreach语句前声明一个变量,在foreach语句中对该变量进行自增运算,还有其他办法吗^_^

PHPz
PHPz

学习是最好的投资!

reply all(2)
黄舟

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template