数组遍历
强化for循环
int[] num={12,46,84,25,28};
for(int a:num){
System.out.println(a);
}
普通for循环
int[] num={12,46,84,25,28};
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
强化for
List<String> num=new ArrayList<>();
//强化for循环
for(String b:num){
System.out.println(b);
}
迭代器
Collection<String> a=new ArrayList<>();
迭代器
Iterator<String> it=a.iterator();//将数据iterator接口对象话,这样就能调用接口里面的功能
while(it.hasNext()){//hasNext()是元素下标,没有就返回false
System.out.println(it.next());//next()下标的元素值,调用一次就移动一位
}
}
List索引获取值
集合.get(索引);
集合.add(索引,元素);
集合.remove(索引);
map集合
Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public String toString() {
return "Peson [name=" + name + ", age=" + age + "]";
}
}
四种遍历方法
public class MapDemo {
/**
* @param args
*/
public static void main(String[] args) {
Map<Integer,Person> map=new HashMap<>();
map.put(1001, new Person("小红", 19));
map.put(1002, new Person("小名", 29));
map.put(1003, new Person("王五", 13));
map.put(1004, new Person("即墨", 29));
map.put(1005, new Person("小花", 14));
System.out.println(map);
founc01(map);
System.out.println("-----------------------");
founc02(map);
System.out.println("-----------------------");
founc03(map);
}
//keyset+增强for循环
public static void founc01(Map<Integer,Person> map){
Set<Integer> set=map.keySet();
for(Integer s:set){
System.out.println(""+s+map.get(s));
}
}
//keySet+迭代器遍历
public static void founc02(Map<Integer,Person> map){
Set<Integer> set=map.keySet();
Iterator<Integer> it=set.iterator();
while(it.hasNext()){
Integer n=it.next();
System.out.println(""+n+map.get(n));
}
}
//entry+增强for循环
public static void founc03(Map<Integer,Person> map){
Set<Map.Entry<Integer, Person>> set=map.entrySet();
for(Map.Entry<Integer, Person> s:set ){
System.out.println(""+s.getKey()+s.getValue());
}
}
//entry+迭代器遍历
public static void founc04(Map<Integer,Person> map){
Set<Map.Entry<Integer, Person>> set=map.entrySet();
Iterator<Entry<Integer, Person>> it=set.iterator();
while(it.hasNext()){
Map.Entry<Integer,Person> n = it.next();
System.out.println(""+it.next().getKey()+n.getValue());
}
}
}
输出
1001Peson [name=小红, age=19]
1002Peson [name=小名, age=29]
1003Peson [name=王五, age=13]
1004Peson [name=即墨, age=29]
1005Peson [name=小花, age=14]