首先看一下MAP,给一个MAP里面放一些值,代码如下:
public class TestMap {
public static void main(String args[]){
Map<String, String> map=new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:通过map.keyset遍历key和value
for(String key:map.keySet()){
String value=map.get(key);
System.out.println("key=="+key+" and value="+value);
}
//第二种:通过map.entryset使用iterator遍历key和value
Iterator<Map.Entry<String, String>> itr=map.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String, String> entry=itr.next();
String key=entry.getKey();
String value=entry.getValue();
System.out.println("key="+key+" value="+value);
}
//第三种:通过map.entryset遍历key和value
for(Map.Entry<String, String> entry:map.entrySet()){
String key=entry.getKey();
String value=entry.getValue();
System.out.println("key="+key+"-------->value="+value);
}
//第四种:直接遍历value
for(String s:map.values()){
System.out.println("value="+s);
}
执行的结果如下:
key==3 and value=value3
key==2 and value=value2
key==1 and value=value1
key=3 value=value3
key=2 value=value2
key=1 value=value1
key=3-------->value=value3
key=2-------->value=value2
key=1-------->value=value1
value=value3
value=value2
value=value1
接下来再谈一下LIST的遍历方法:
这个方法里面我list里面放的是USER对象,先建一个对象代码如下:
package com.cn.domain;
public class Gost {
private long id;
private String name;
private String password;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
接下来写了一个类来测试,首先给LIST里放入一些数据,代码如下:
package test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.cn.domain.Gost;
public class TestList {
public static void main(String args[]){
List<Gost> gostlist=new ArrayList<Gost>();
Gost gost1=new Gost();
gost1.setId(1);
gost1.setName("z3");
gost1.setPassword("111");
gostlist.add(gost1);
Gost gost2=new Gost();
gost2.setId(2);
gost2.setName("l4");
gost2.setPassword("222");
gostlist.add(gost2);
Gost gost3=new Gost();
gost3.setId(3);
gost3.setName("w5");
gost3.setPassword("333");
gostlist.add(gost3);
接下来就是三种遍历的方法,代码如下:
//方法1:加强for循环
for(Gost s:gostlist){
System.out.println(s.getId()+"--"+s.getName()+"--"+s.getPassword());
}
//方法2:for循环
for(int i=0;i<gostlist.size();i++){
Gost gost=gostlist.get(i);
System.out.println(gost.getId()+"-"+gost.getName()+"-"+gost.getPassword());
}
//方法3,iterator
Iterator it=gostlist.iterator();
while(it.hasNext()){
Gost gost=(Gost) it.next();
System.out.println(gost.getId()+"-"+gost.getName()+"-"+gost.getPassword());
}
执行程序的结果为:
1--z3--111
2--l4--222
3--w5--333
1-z3-111
2-l4-222
3-w5-333
1-z3-111
2-l4-222
3-w5-333