/** * Returns a {@link Set} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. */ public Set<K> keySet() { return navigableKeySet(); }
TreeSet 底层是通过 TreeMap 来实现的 TreeSet set = TreeMap.getKeySet(); 这样 set 就是默认有序的
* Returns a {@link Set} view of the keys contained in this map.
* The set's iterator returns the keys in ascending order.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*/
public Set<K> keySet() {
return navigableKeySet();
}
TreeSet set = TreeMap.getKeySet();
这样 set 就是默认有序的
Iterator ir=map.keySet().iterator();//获取hashMap的键值,并进行遍历
while(ir.hasNext()){
Object key= ir.next();
System.out.println("键为"+key+"所对应的值为"+map.get(key));
}
即是通过TreeMap中指针的移动,实现对TreeMap的遍历
Set只保证元素的唯一性。
public interface NavigableSet<E> extends SortedSet<E>{......}