继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

以Student为例子的array,list,set,map比较

刘鑫同学
关注TA
已关注
手记 2
粉丝 2
获赞 3

Student.java


public class Student {
	private String id;
	private String password;
	private String name;
	public Student(String id, String password, String name) {
		super();
		this.id = id;
		this.password = password;
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public String getPassword() {
		return password;
	}
	public String getName() {
		return name;
	}
	
	
}

Main.java

import Student;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class Initial {
	public static void listForEach(List<Student> ls) {
		for(Student temp: ls) {
			System.out.println(temp.getId()+temp.getName());
		}
	}
	
	public static void setForEach(Set<Student> st) {
		for(Student temp: st) {
			System.out.println(temp.getId() + temp.getName());
		}
	}
	
	//必须用Student temp = mp.get(key);
	public static void mapForEach(Map<String,Student> mp) {
		Set<String> keySet = mp.keySet();
		for (String key: keySet) {
			Student temp = mp.get(key);
			if(temp != null) {
				System.out.println(temp.getId() + temp.getName());
			}
		}
	}
	
	public static void main(String[] args) {
		// 实例:创建s1对象,并读取属性
		//Student s1 = new Student("1","123456","Tom");		
		//System.out.println(s1.getId());
		
		// 创建多个对象		
		Student[] studentArray = {
				new Student("1","123456","Tom"),
				new Student("2","123456","Harry"),
				new Student("3","123456","William")};
		// System.out.println(studentArray[2].getId());
		
		Student s1 = studentArray[0];
		Student s2 = studentArray[1];
		Student s3 = studentArray[2];
		
		// List, ArrayList
		List<Student> studentList = new ArrayList<Student>();
		studentList.add(s1);
		studentList.addAll(0, Arrays.asList(Arrays.copyOfRange(studentArray, 1, 3)));
		Student temp = studentList.get(0);
		System.out.println(temp.getName() + " 地址:" + temp);
		listForEach(studentList);
		
		// Set HashSet
		Set<Student> studentSet = new HashSet<Student>();
		studentSet.addAll(Arrays.asList(studentArray));
		setForEach(studentSet);
		
		// Map HashMap
		Map<String,Student> studentMap = new HashMap<String, Student>();
		studentMap.put(s1.getId(), s1);
		studentMap.put(s2.getId(), s2);
		studentMap.put(s3.getId(), s3);
		Student temp2 = studentMap.get("2");
		System.out.println(temp2.getName() + " 地址:"  + temp2);
		mapForEach(studentMap);
		
		
	}	
}

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP