form1.cn
Make a little progress every day

集合框架Collection与Map的区别和基本使用

29th of June 2017 Java Java 1659

Collection接口,包含list、Queue和set子接口 (Queue接口不常用)

list是有序的,set是无序的

Collection和Map接口之间的主要区别在于:Collection中存储了一组对象,而Map存储关键字/值对。

在Map对象中,每一个关键字最多有一个关联的值。

Map:不能包括两个相同的键,一个键最多能绑定一个值。null可以作为键,这样的键只有一个;可以有一个或多个键所对应的


以下为测试代码,包括Compara...接口中排序的使用


Course类

package cn.form1;

public class Course {
	public String id;
	public String name;
	public Course(){}
	public Course(String id,String name){
		this.id = id;
		this.name = name;
	}
	
	//重写方法会自动添加 需适当修改
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime  result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Course))
			return false;
		Course other = (Course) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
}


Student类

package cn.form1;

import java.util.HashSet;
import java.util.Set;

public class Student implements Comparable<Student> {

	public String id;
	public String name;
	public Set<Course> course;
	public Student(String id,String name){
		this.id = id;
		this.name = name;
		this.course = new HashSet<Course>();
	}
	
	//重写方法会自动添加 需适当修改
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime  result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Student))
			return false;
		Student other = (Student) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		return this.id.compareTo(o.id);
	}
}


ListTest类,测试List

package cn.form1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ListTest {

	public List<Course> courseToSelect;
	private Scanner sc;
	public ListTest(){
		this.courseToSelect = new ArrayList<Course>();
	}
	
	//list添加
	public void listAdd(){
		Course cr1 = new Course("1", "php课程");
		this.courseToSelect.add(cr1);//cr1会以object对象类型加入
		Course course = (Course)this.courseToSelect.get(0);//调用list中第一个对象,需要强转类型
		System.out.println("加入了课程:" + course.id + " - " + course.name );
		
		Course cr2 = new Course("2", "孟浩");
		this.courseToSelect.add(0,cr2);//add方法指定位置插入
		Course course2 = (Course)this.courseToSelect.get(0);
		System.out.println("加入了课程:" + course2.id + " - " + course2.name);
		//注:下标不能越界,否则会报下标溢出异常
		
		Course[] temp1 = {new Course("3", "许清"),new Course("4", "王有财")};
		this.courseToSelect.addAll(Arrays.asList(temp1));//addAll 批量添加
		Course course3 = (Course)this.courseToSelect.get(2);
		System.out.println("加入了课程:" + course3.id + " - " + course3.name);
		
		Course[] temp2 = {new Course("5", "李富贵"),new Course("6", "楚语嫣")};
		this.courseToSelect.addAll(2,Arrays.asList(temp2));//addAll 指定位置批量添加
		Course course4 = (Course)this.courseToSelect.get(2);
		System.out.println("加入了课程:" + course4.id + " - " + course4.name);
		
		this.courseToSelect.add(3,cr1);//cr1会以object对象类型加入
		Course course0 = (Course)this.courseToSelect.get(0);//调用list中第一个对象,需要强转类型
		System.out.println("加入了课程:" + course0.id + " - " + course0.name );
		
		System.out.println(this.courseToSelect.size());
		
	}
	
	//list打印
	public void testGet(){
		int size = this.courseToSelect.size();
		
		System.out.println("FOR打印===================:");
		for(int i = 0; i < size; i++){
			Course cr = (Course)this.courseToSelect.get(i);
			System.out.println(cr.id +" : " + cr.name);
		}
		
		System.out.println("FOR EACH打印===================:");
		for(Course cr1 : this.courseToSelect){
			System.out.println(cr1.id +" : " + cr1.name);
		}
		
		this.courseToSelect.set(4, new Course("9","呼延老祖"));//修改
		System.out.println("FOR EACH打印===================:");
		for(Course cr1 : this.courseToSelect){
			System.out.println(cr1.id +" : " + cr1.name);
		}
		
		this.courseToSelect.remove(4);//所引删
		System.out.println("FOR EACH打印===================:");
		for(Course cr1 : this.courseToSelect){
			System.out.println(cr1.id +" : " + cr1.name);
		}
		
		Course[] reall = {(Course)this.courseToSelect.get(4),(Course)this.courseToSelect.get(5)};
		this.courseToSelect.removeAll(Arrays.asList(reall));//批量删
		System.out.println("FOR EACH打印===================:");
		for(Course obj : this.courseToSelect){
			System.out.println(obj.id +" : " + obj.name);
		}
	}
	
	//set用法  set 不可重复  并且 无序,,其它方法和list使用相似
	public void students(){
		Student stu = new Student("1", "陈凡");
		System.out.println("欢迎"+stu.name+"选课");
		sc = new Scanner(System.in);
		for(int i = 0; i < 3; i++){
			System.out.println("请输入选择的课程ID号:");
			String sid = sc.next();
			for(Course cr1 : this.courseToSelect){
				if(cr1.id.equals(sid)){//如果课程ID存在
					stu.course.add(cr1);//加入到学生课程集合中
				}
			}
		}
		
		System.out.println("共选择了"+stu.course.size()+"个课程");
		
		for(Course cr2 : stu.course){
			System.out.println(cr2.id+" - "+cr2.name);
		}
		
		Course course = new Course("2", "孟浩");
		boolean isnull = stu.course.contains(course);//set.contains方法,需要重写hashCode
		System.out.println(isnull);//无序所以无索引
	}
	
	//list.contains用法,需要重写equals
	public void contains(){
		Course course = new Course("1", "php课程");//判断 课程集合中是否包含 某个课程,,需要先把该课程组装为对像
		boolean isnull = this.courseToSelect.contains(course);//list.contains用法,需要重写equals
		System.out.println(isnull+" - 索引 :"+ this.courseToSelect.indexOf(course));
		//indexOf 存于集合中对应对象的索引位置
	}
	
	public static void main(String[] args) {
		ListTest lt = new ListTest();
		lt.listAdd();
		//lt.testGet();
		//lt.students();
		lt.contains();
	}

}


TestMap类,测试map

package cn.form1;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class TestMap {

	public Map<String,Student>students;
	private Scanner san;
	
	public TestMap(){
		this.students = new HashMap<String,Student>();
	}
	
	public void Mapstudent(){
		san = new Scanner(System.in);
		int i = 0;
		while(i < 3){
			System.out.println("请输入学生ID号");
			String ID = san.next();//添加到map中的 key
			Student st = this.students.get(ID);
			if(st == null){
				System.out.println("请输入学生的姓名:");
				String sname = san.next();
				Student student = new Student(ID, sname);//添加到map中的value
				this.students.put(ID, student);//put添加到map集合中
				System.out.println("已添加学生:"+ sname);
			}else{
				System.out.println("该学生已存在");
				continue;
			}
			i++;
		}
	}
	
	//entrySet的方式打印map
	public void entrySet(){
		Set<Entry<String, Student>> entry = this.students.entrySet();
		for(Entry<String, Student> entr : entry){
			System.out.println("key : " + entr.getKey());
			System.out.println("valu: " + entr.getValue().name);
		}
	}
	
	//使用 keySet 方式,打印map集合数据
	public void keySet(){
		System.out.println("---------打印所有学生----------");
		Set<String> key = this.students.keySet();
		for(String ky : key){
			Student st = this.students.get(ky);//get调用map中的key获取value
			System.out.println("学生ID:"+ st.id + "--学生姓名:"+st.name);
		}
	}
	
	//删除对应key的value
	public void reMove(){
		san = new Scanner(System.in);
		while(true){
			System.out.println("请输入要删除的学生ID:");
			String ID = san.next();
			Student stu = this.students.get(ID);
			if(stu == null){
				System.out.println("学生ID不存在...");
				continue;
			}else{
				this.students.remove(ID);//删除对应key的对象
				System.out.println("成功删除学生:"+stu.name);
				break;
			}
		}
	}
	
	//修改对应key的对象
	public void modify(){
		san = new Scanner(System.in);
		while(true){
			System.out.println("请输入要修改的学生ID:");
			String ID = san.next();
			Student stu = this.students.get(ID);
			if(stu == null){
				System.out.println("学生ID不存在...");
				continue;
			}else{
				System.out.println("即将要修改的学生是:"+stu.name);
				System.out.println("输入新的学生名称");
				String name = san.next();
				Student stu2 = new Student(ID, name);
				this.students.put(ID, stu2);//修改
				break;
			}
		}
	}
	
	
	
	//map中containskey 与 containsvalue用法
	public void containskey_value(){
		String ID = "2";
		boolean iskey = this.students.containsKey(ID);
		System.out.println("containskey----------判断key是否存在");
		if(iskey){//如果判断 map中 key 存在,输出 该key对应对像中学生的姓名
			System.out.println("学生姓名:"+ this.students.get(ID).name +" - "+ iskey);
		}
		String Name = "小红";
		Student student = new Student(null, Name);
		boolean isvalue = this.students.containsValue(student);//判断map.containsValue 需要重写equals方法
		System.out.println("containsvalue----------判断value是否存在");
		if(isvalue){
			System.out.println("学生存在于Map集合中" +" - "+isvalue);
		}
	}
	
	public static void main(String[] args) {
		TestMap testmap = new TestMap();
		testmap.Mapstudent();
		testmap.keySet();
		testmap.reMove();
		testmap.entrySet();
		testmap.modify();
		testmap.entrySet();
		testmap.containskey_value();
	}

}


CollectionTest类,测试排序

package cn.form1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionTest {

	//对int的包装类integer排序
	//创建一个 10 个随机数的 list 对其进行排序
	public void integerSort(){
		List<Integer> integerList = new ArrayList<Integer>();
		Random random = new Random();//产生随机数的类
		Integer k = new Integer(0);//实例化一个int的包装类
		for(int i = 0; i < 10; i++){
			do{//保证随机数唯一的方法
				k = random.nextInt(100);
			}while(integerList.contains(k));//如果k已存在于 integerList 会重新随机
			integerList.add(k);//添加到 integerList 中
			System.out.println("成功添加整数:"+k);
		}
		System.out.println("---------排序前--------");
		for(Integer vo : integerList){
			System.out.println(vo);
		}
		System.out.println("---------排序后--------");
		Collections.sort(integerList);//是 Collections 工具类的 sort 排序方法
		for(Integer vo : integerList){
			System.out.println(vo);
		}
	}
	
	//对String的包装类String排序
	//创建一个 10 个随机字符串的 list 对其进行排序
	public void stringSort(){
		List<String> stringList = new ArrayList<String>();
		Random random = new Random();
		for(int i = 0; i < 10; i++){
			String str = this.getRandomString(random.nextInt(10));//随机生成 0-10长度的字符串
			System.out.println("成功添加字符串:"+ str);
			stringList.add(str);
		}
		System.out.println("---------排序前--------");
		for(String str : stringList){
			System.out.println(str);
		}
		System.out.println("---------排序后--------");
		Collections.sort(stringList);//是 Collections 工具类的 sort 排序方法
		for(String str : stringList){
			System.out.println(str);
		}
	}
	
	//对学生类 Student 进行排序,需要学生类 实现 Comparable 接口中的compareTo方法
	public void studentSort(){
		List<Student> student = new ArrayList<Student>();
		Random random = new Random();
		student.add(new Student(random.nextInt(1000)+"", "丹鬼大师"));
		student.add(new Student(random.nextInt(1000)+"", "金寒宗老祖"));
		student.add(new Student(random.nextInt(1000)+"", "帝宗老祖"));
		//注:数值排序 要用 int类型,否则 1000 会 排在 2的上面
		System.out.println("---------默认以ID排序后--------");
		Collections.sort(student);
		//Collections.sort 排序  学生类 实现 Comparable 接口中的CompareTo方法
		for(Student stu : student){
			System.out.println(stu.id+" - "+stu.name);
		}
		System.out.println("---------临时以name排序后--------");
		Collections.sort(student,new StudentComparator());//StudentComparator 为临时排序规则
		for(Student stu : student){
			System.out.println(stu.id+" - "+stu.name);
		}
	}
	
	//随机生成字符串
	public String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();     
	    if (length <= 1) length = 3;
	    StringBuffer sb = new StringBuffer();//初始化可变字符串
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());//得到一个随机位置 
	        sb.append(base.charAt(number));//charAt 获取字符中指定位置的 字符
	    }     
	    return sb.toString();//转为String返回
	 }   
	
	public static void main(String[] args) {
		CollectionTest cot = new CollectionTest();
		cot.integerSort();
		cot.stringSort();
		cot.studentSort();
	}

}


StudentComparator类,测试临时排序规则

package cn.form1;

import java.util.Comparator;

//临时排序规则接口
public class StudentComparator implements Comparator<Student> {

	@Override
	public int compare(Student o1, Student o2) {
		// 对 Student 的 name 进行排序
		return o1.name.compareTo(o2.name);
	}

}