为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java

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);
		
		
	}	
}

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消