遍历List,Set的方法

来源:互联网 发布:开淘宝网店要多钱 编辑:程序博客网 时间:2024/06/07 01:46

一:ArrayList,LinkedList,Vector遍历方法一样 

List<String> list = new ArrayList<String>();

        //方法1
        Iterator it1 = list.iterator();
        while(it1.hasNext()){
            System.out.println(it1.next());
        }

        //方法2
        for(String tmp:list){
            System.out.println(tmp);
        }

        //方法3
        for(int i = 0;i < list.size(); i ++){
            System.out.println(list.get(i));
        }

二:hashmap遍历方法  put(key,value)

方法一:效率比方法二高

for(Entry<Integer, String> entry:map.entrySet())
  {
   System.out.println(entry.getKey()+"="+entry.getValue());
  }

Entry是Map实现类的内部类。Entry是Map中用来保存一个键值对的,而Map实际上就是多个Entry的集合。

方法二:

for(Object obj : map.keySet()) {     
      Object key = obj;     
      Object value = map.get(obj);     
      System.out.println(value);
  }

三:遍历hashset:add(E e)

for(Iterator it=set.iterator();it.hasNext();)
  {
   System.out.println(it.next());
  }

四 遍历Hashtable(同步、线程安全的)

Hashtable table = new Hashtable();
  table.put(1, "1");
  table.put(2, "1");
  table.put(3, "1");
  //遍历key
  Enumeration e = table.keys();

  while( e. hasMoreElements() ){

  System.out.println( e.nextElement() );

  }
  //遍历value
  e = table.elements();

  while( e. hasMoreElements() ){

  System.out.println( e.nextElement() );

  }

原创粉丝点击