数组和集合的遍历

数组遍历
强化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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值