标签:[] 图片 优化 keyset map range col odi tran
集合类的通用遍历方式, 用迭代器迭代:
//Set<Integer> set = map.keySet(); //得到所有key的集合 for (Integer in : map.keySet()) { String str = map.get(in);//得到每个key多对用value的值 }
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, String> entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
for (Map.Entry<Integer, String> entry : map.entrySet()) { //Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry //entry.getKey() ;entry.getValue(); entry.setValue(); //map.entrySet() 返回此映射中包含的映射关系的 Set视图。 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
for (String v : map.values()) { System.out.println("value= " + v); }
for(Iterator iterator = list.iterator();iterator.hasNext();){ int i = (Integer) iterator.next(); System.out.println(i); }
Iterator iterator = list.iterator(); while(iterator.hasNext()){ int i = (Integer) iterator.next(); System.out.println(i); }
for (Object object : list) { System.out.println(object); }
for(int i = 0 ;i<list.size();i++) { int j= (Integer) list.get(i); System.out.println(j); }
transient Object[] elementData; public E get(int index) { rangeCheck(index); return elementData(index); } E elementData(int index) { return (E) elementData[index]; }
LinkedList按位置读取的代码:每次都需要从第0个元素开始向后读取。其实它内部也做了小小的优化。
transient int size = 0; transient Node<E> first; transient Node<E> last; public E get(int index) { checkElementIndex(index); return node(index).item; } Node<E> node(int index) { if (index < (size >> 1)) { //查询位置在链表前半部分,从链表头开始查找 Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { //查询位置在链表后半部分,从链表尾开始查找 Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; }
if (list instanceof RandomAccess) { //使用传统的for循环遍历。 } else { //使用Iterator或者foreach。
标签:[] 图片 优化 keyset map range col odi tran
原文地址:https://www.cnblogs.com/yangwenzhe/p/9117980.html