HashMap排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("a", "a_Value");
        map.put("b", "b_Value");
        map.put("c", "c_Value");
        map.put("d", "d_Value");
        map.put("e", "e_Value");
        System.out.print("原始顺序:\n");
        for (String key : map.keySet()) {
            System.out.print("key:" + key);
            System.out.print("\n");
        }
        System.out.print("\n");
        System.out.print("排序后:\n");
        List<String> list = new ArrayList<String>(map.keySet());
        Collections.sort(list);
        for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
            System.out.print("key:" + ite.next());
            System.out.print("\n");
        }

    }
}


1 HashMap本身不保证元素的有序性,即使你是按照顺序放进去的

2 Iterator是一个接口,该接口提供了访问容器内部数据的方法,支持简单的按顺序遍历

private class ArrayListIterator implements Iterator<E> {
        /** Number of elements remaining in this iteration */
        private int remaining = size;

        /** Index of element that remove() would remove, or -1 if no such elt */
        private int removalIndex = -1;

        /** The expected modCount value */
        private int expectedModCount = modCount;

        public boolean hasNext() {
            return remaining != 0;
        }

        @SuppressWarnings("unchecked") public E next() {
            ArrayList<E> ourList = ArrayList.this;
            int rem = remaining;
            if (ourList.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            if (rem == 0) {
                throw new NoSuchElementException();
            }
            remaining = rem - 1;
            return (E) ourList.array[removalIndex = ourList.size - rem];
        }

        public void remove() {
            Object[] a = array;
            int removalIdx = removalIndex;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            if (removalIdx < 0) {
                throw new IllegalStateException();
            }
            System.arraycopy(a, removalIdx + 1, a, removalIdx, remaining);
            a[--size] = null;  // Prevent memory leak
            removalIndex = -1;
            expectedModCount = ++modCount;
        }
    }

ourList.array就是容器ArrayList的内部数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值