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的内部数据