List<Object> objList = new ArrayList<Object>();
1) for (int i=0; i<objList.size; i++)
{
// 循环输出集合中的每个对象
Object object = objList.get(i);
System.out.println(object);
}
2) for (Object obj:objList)
{
// 循环输出集合中的每个对象
System.out.println(object);
}
3) 将List集合转换为迭代器Iterator接口,并且循环输出
List<String> list = new ArrayList<String>();
list.add("cheng");
list.add("zeng");
list.add("zhang");
Iterator it = list.iterator();
while (it.hasNext())
{
String str = (String)it.next();
System.out.println(str);
}
4) 将List集合转换为Object类型的数组,循环输出
List<String> list = new ArrayList<String>();
list.add("cheng");
list.add("zeng");
list.add("zhang");
Object[] obj = list.toArray();
for (int i=0; i<obj.length; i++)
{
String s = (String)obj[i];
System.out.println(s);
}
二.循环输出Set<E>
1) 将Set集合转换为迭代器Iterator接口,并且循环输出
Set<String> set = new HashSet<String>();
set.add("cheng");
set.add("zeng");
set.add("zhang");
Iterator it = set.iterator();
while (it.hasNext())
{
String str = (String)it.next();
System.out.println(str);
}
2) 将Set集合转换为Object类型的数组
Set<String> set = new HashSet<String>();
set.add("cheng");
set.add("zeng");
set.add("zhang");
Object[] obj = set.toArray();
for (int i=0;i<obj.length;i++)
{
String s = (String)obj[i];
System.out.println(s);
}
三.循环输出Map<K,V>
1) 直接循环Map对象
Map<String,String> map = new HashMap<String, String>();
map.put("1","cheng");
map.put("2","zeng");
map.put("3","zhang");
// 输出键值
for (String key:map.keySet())
{
System.out.println(key);
}
// 输出value
for (String value:map.values())
{
System.out.println(value);
}
2) Map<String,String> map = new HashMap<String, String>();
map.put("1","cheng");
map.put("2","zeng");
map.put("3","zhang");
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<String, String> s = (Map.Entry<String, String>)it.next();
System.out.println(s);
}
输出结果:
3=zhang
2=zeng
1=cheng
public class Test {
public static void main(String[] args) {
//范型 避免因类型强转而产生的错误
List<Student> list = new ArrayList<Student>();
list.add(new Student(1,"dfd"));
list.add(new Student(4,"hfg"));
list.add(new Student(2,"dsf"));
list.add(new Student(8,"fgfg"));
第一种方式:for循环
//遍历List集合里的内容 只对List有效 因为List是有序的集合
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i).id+" "+list.get(i).name);
}
第二种方式:iterator迭代器
//迭代器方式 弱点是只能从头到尾 兼容性最好 适合于Collection集合
Iterator<Student> it = list.iterator();
while(it.hasNext()){//hasNext()判断有没有下一个元素
Student st = it.next();
System.out.println(st.id+" "+st.name);
}
第三种方式:for each
//for each 方式本质还是迭代器 每循环一次 放的就是当前对象的地址 适合List Set Map
//只能在JK1.5以上使用 兼容性不好 Set最好用这种
for(Student t:list){
System.out.println(t.id+" "+t.name);
}
遍历Set集合和List的方式一样 不过不能使用for 循环来遍历Set集合 因为Set集合中没有get()方法
//遍历Set集合
Set<Student> set = new HashSet<Student>();
set.add(new Student(2,"dfd"));
set.add(new Student(4,"gdfg"));
set.add(new Student(1,"sadf"));
set.add(new Student(8,"df"));
for(Student t:set){
System.out.println(t.id+" "+t.name);
}
}
}