关闭

慕课网3.2 Collection接口 List 接口 Set接口 Map接口

365人阅读 评论(0) 收藏 举报
分类:

4.

 

4-1  集合框架概述


4-9 泛型

规定某个集合只可以存放特定类型及其子类型的对象

会在编译期间进行类型检查

不能是基本类型,必须是引用类型

List<Course> courses=new ArrayList<course>();

Course cr1=new Course(“1”,”d”);

Courses.add(cr1);

For(Course cr:Coirses)

System.out.println(cr.ld); 

4-11 Set 接口

元素无序且不可以重复的集合

可以添加空元素null

Collection 接口  工具类

Contains.(obj)--->  hascode()+equals()

Indexof(obj)---->equals()  无返回-1

Lastindexdof(obj)---->无返回-1

 

5-1 Map & HashMap简介

Key-value    不可重复  Map<k,v>支持泛型

Void clear()

Boolean containsKey(Object key)  //如果映射包含指定键的映射关系,则返回true

Boolean containsValue(Object value) 

V get(Object key) //返回指定键所映射的值,若不存在,则返回null

Boolean isEmpty()

V put(k key,v value)

V remove(Object key)

Set<K> keySet() //返回此映射中所包含的键的set视图

Set<Map.Entry<k,v>>  entrySet() //键值对  的集合

 

6-5 collections.sort() 排序

List<Interger>

List<包装类>

 

Comparable()接口,默认比较规则,实现compareTo()方法

Comparator()临时比较规则,compare()方法

 

字符串比较规则:先数字后字母,数字0-9,字母A-Za-z的顺序

 


1. Course.java

package com.imocc.collection;
/**
 * 课程类
 * @author Administrator 
 */
public class 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 Course))  //类型  
	            return false;  
	        Course course=(Course)obj;  //强制转换类型  
	        if(this.name==null){  
	            if(course.name==null)  
	                return true;  
	            else  
	                return false;  
	        }else{  
	            if(this.name==null)  
	                return false;  
	            else if(this.name.equals(course.name))  
	                return true;  
	            else  
	                return false;  
	        }  
	    }  
	public String id;
	public String name;
	public Course(String id,String name){
		this.id=id;
		this.name=name;
	}
	
	public Course(){
		
	}
}



2.ChildCourse

package com.imocc.collection;
/**
 * 课程类
 * @author Administrator 
 */
public class Course {
	public String id;
	public String name;
	public Course(String id,String name){
		this.id=id;
		this.name=name;
	}
	
	public Course(){
		
	}
}

3.ListTest

package com.imocc.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

/**
 * 备选课程类
 * @author Administrator
 *
 */
public class ListTest {
	public List coursesToSelect;   //用于存放备选课程的容器
	public ListTest(){
		this.coursesToSelect=new ArrayList();
	}
	public void add(){   //用于添加备选课程
		Course cr1=new Course("1","数据结构");
		coursesToSelect.add(cr1);		
		
		Course cr2=new Course("2","C语言");
		coursesToSelect.add(0,cr2);
		
		Course temp=(Course)(coursesToSelect.get(0));
		System.out.println("添加了课程: "+temp.id +" "+temp.name);
	
		Course[] course =new Course[]{new Course("3","C++"),new Course("4","java")};
		coursesToSelect.addAll(Arrays.asList(course));
		
		Course temp2=(Course)(coursesToSelect.get(2));
		Course temp3=(Course)(coursesToSelect.get(3));
		System.out.println("添加了两门课程: "+temp2.id +" "+temp2.name+";"+temp3.id +" "+temp3.name);
		
		Course[] course2 =new Course[]{new Course("5","C#"),new Course("6","VB")};
		coursesToSelect.addAll(2,Arrays.asList(course2));
		
		Course temp4=(Course)(coursesToSelect.get(2));
		Course temp5=(Course)(coursesToSelect.get(3));
		System.out.println("添加了两门课程: "+temp4.id +" "+temp4.name+";"+temp5.id +" "+temp5.name);		
	}
	
	/**
	 * 取得List的元素
	 * 
	 */
	public void testSet(){
		int size=coursesToSelect.size();
		System.out.println("有如下课程待选");
		for(int i=0;i<size;i++){
			Course temp=(Course)(coursesToSelect.get(i));
			System.out.println(temp.id +" "+temp.name);
			
		}
	}
	
	/**
	 * 通过迭代器取得List的元素
	 */
	public void testIterator(){
		System.out.println("集合内元素如下:");
	    Iterator it=coursesToSelect.iterator();
		while(it.hasNext()){
			Course cr=(Course)it.next();
			System.out.println(cr.id +" "+cr.name);
		}
	}
	
	/**
	 * 通过Forreach取得List的元素
	 */
	public void testForreach(){
		System.out.println("集合内元素如下:");		
		for(Object obj:coursesToSelect){
			Course cr=(Course)obj;
			System.out.println(cr.id +" "+cr.name);
		}
	}
	
	/**
	 * 修改元素
	 */
	public void testModify(){
		coursesToSelect.set(4, new Course("7","毛"));
	}
	
	
	/**
	 * 删除元素
	 */
	public void testDelete(){
		Course[] crs={(Course)coursesToSelect.get(2),(Course)coursesToSelect.get(3)};
		coursesToSelect.removeAll(Arrays.asList(crs));
	}
	
	/**
	 * 能否往list中添加一些奇怪的东西
	 * 运行期  抛出异常 java.lang.String cannot be cast to com.imocc.collection.Course
	 */
	public void testType(){
		//coursesToSelect.add("我是一个奇怪的类型");    
	}
	
	/**
	*测试contains
	*/
	public void testListContains(){
		Course course = (Course) coursesToSelect.get(0);
		System.out.println("取得课程:"+course.name);
		System.out.println("备选课程中是否包含课程:"+course.name+","+coursesToSelect.contains(course)); //true
		
		System.out.print("输入课程名称");
		Scanner input=new Scanner(System.in);
		String name=input.next();
		Course course2 =new Course(course.id,name);
		System.out.println("取得课程:"+course2.name);
		System.out.println("备选课程中是否包含课程:"+course2.name+","+coursesToSelect.contains(course2));//若不改写equals则返回false;
	}



	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ListTest test=new ListTest();
		test.add();
		//test.testSet();
		//test.testIterator();
		
		test.testDelete();
		test.testForreach();
		
		test.testType();
		test.testForreach();  //抛出异常 java.lang.String cannot be cast to com.imocc.collection.Course
		
		test.testListContains();
	}

}


4.TestGeneirc   泛型    

package com.imocc.collection;

import java.util.ArrayList;
import java.util.List;

public class TestGeneirc {
	public List<Course> courses;
	//public List<int> courses2;  基本类型不能用作特定类型,只能使用引用类型
	public TestGeneirc(){
		this.courses=new ArrayList<Course>();
	}
	
	//添加元素
	public void testAdd(){
		Course cr1=new Course("1","d");
		courses.add(cr1);
	    //course.add("fsd");   //不能添加指定类型及其子类型以外的对象,编译器出错
		
		Course cr2=new Course("2","k");
		courses.add(cr2);
	}
	
	//遍历元素
	public void testForeach(){
		for(Course cr:courses){
			System.out.println(cr.id +" "+cr.name);
		}
	}
	
	
	/**
	 * 泛型集合可以添加子类类型的对象实例
	 */
	public void testChild(){
		 ChildCourse  cc=new  ChildCourse ();
		 cc.id="3";
		 cc.name="我是子类型的特征对象实例";
		 courses.add(cc);
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestGeneirc  test=new TestGeneirc ();
		test.testAdd();
		test.testForeach();
		test.testChild();
		test.testForeach();
		
	}

}


5.Student 

package com.imocc.collection;
import java.util.HashSet;
import java.util.Set;

public class Student {
	public String id;
	public String name;
	public Set<Course> courses;
	
	public Student(String id,String name){
		this.id=id;
		this.name=name;
		this.courses=new HashSet<Course>();
	}
}


6.  SetTest

package com.imocc.collection;

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

public class setTest {
	public List<Course> coursesToSelect;
	
	public Scanner console;
	public setTest(){
		this.coursesToSelect=new ArrayList<Course>();
		console = new Scanner(System.in);
	}
	public void testAdd(){
		Course cr1=new Course("1","数据结构");
		coursesToSelect.add(cr1);	
		
		Course cr2=new Course("2","C语言");
		coursesToSelect.add(0,cr2);
		
		Course[] course =new Course[]{new Course("3","C++"),new Course("4","java")};
		coursesToSelect.addAll(Arrays.asList(course));
		
		Course[] course2 =new Course[]{new Course("5","C#"),new Course("6","VB")};
		coursesToSelect.addAll(2,Arrays.asList(course2));
		
		Course temp4=(Course)(coursesToSelect.get(2));
		Course temp5=(Course)(coursesToSelect.get(3));
		System.out.println("添加了两门课程: "+temp4.id +" "+temp4.name+";"+temp5.id +" "+temp5.name);		
	}
	
	//遍历元素
	public void testForeach(){
		for(Course cr:coursesToSelect){
			System.out.println(cr.id +" "+cr.name);
		}
	}
	
	/**
	 * 测试test的contains方法
	 */
	public  void testSetContains(Student student){
		System.out.print("请输入学生已选的课程名称");
		String name=console.next();
		Course course2=new Course();
		course2.name=name;
		System.out.print("新创建课程:"+name);
		System.out.println("备选课程中是否包含课程:"
				+name+","+student.courses.contains(course2)); //true
		if(student.courses.contains(course2)){
			System.out.print("课程:"+name+"的索引位置为"+coursesToSelect.indexOf(course2));
		}
	}
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		setTest test=new setTest();
		
		test.testAdd();
		test.testForeach();
		
		//创建一个学生对象
		Student st=new Student("1","小明");
		System.out.println("欢迎"+st.name+"同学选课");
		Scanner sc=new Scanner(System.in);
		for(int i=0;i<3;i++){
			System.out.println("请输入课程id");
			String id=sc.next();
			for(Course cr:test.coursesToSelect){
				if(cr.id.equals(id)){
					st.courses.add(cr);
					st.courses.add(cr);  //set中不可重复,添加了也无效
				}
			}
		}
		
		System.out.println("打印输出,学生所选课程:  "+st.courses.size());   //3
	
		for(Course cr:st.courses){
			System.out.println(cr.id +" "+cr.name);
		}
		
		st.courses.add(null);//可以添加null
		System.out.println("打印输出,学生所选课程:  "+st.courses.size());   //4
		

		test.testSetContains(st);
	}

}


7.Map

package com.imocc.collection;

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

public class MapTest {
	public Map<String,Student> students;
	
	/**
	 * 构造方法
	 */
	public MapTest(){
		this.students=new HashMap<String,Student>();
	}
	
	/**
	 * 测试添加
	 */
	public void addTest(){
		Scanner input=new Scanner(System.in);
		for(int i=0;i<3;){
			System.out.println("请输入学生id");
			String id=input.next();			
			if(students.containsKey(id)==true){
				System.out.println("该学生id已被占用");
			}
			else{
				i++;
				System.out.println("请输入学生name");
				String name=input.next();
				students.put(id, new Student(id,name));
				System.out.println("成功添加学生:"+id+" "+name);
			}
		}
	}
	
	/**
	 * 遍历   keySet()
	 */
	public void testKeySet(){
		Set<String> keySet=students.keySet();
		for(String id:keySet){
			System.out.println(id+" "+students.get(id).name);
		}
	}
	
	/**
	 * 遍历   entrySet()
	 */
	public void testEntrySet(){
		Set<Entry<String,Student>> keySet=students.entrySet();
		for(Entry<String,Student> id:keySet){
			System.out.println("学生: "+id.getKey()+" "+id.getValue().name);
		}
	}
	
	/**
	 * 删除
	 */
	public void testRemove(){
		System.out.println("请输入要删除的学生id");	
		Scanner input=new Scanner(System.in);
		while(true){
			String id=input.next();				
			Student st=students.get(id);
			if(st==null){
				System.out.println("该id不存在,请重新输入");
				continue;
			}else{
				students.remove(id);
				System.out.println("成功删除学生"+st.name);
				break;
			}
		}
	}
	
	/**
	 * 修改
	 */
	public void testModify(){	
		System.out.println("请输入要修改的学生id");	
		Scanner input=new Scanner(System.in);		
		while(true){
			String id=input.next();		
			Student st=students.get(id);
			if(st==null){
				System.out.println("该id不存在,请重新输入");
				continue;
			}else{
				System.out.println("当前id所对应学生姓名"+st.name);
				System.out.println("重新输入新的学生姓名");
				String name=input.next();	
				students.put(id,new Student(id,name));
				System.out.println("修改成功!");
				break;				
			}			
		}
		}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MapTest test=new MapTest();
		test.addTest();
		test.testKeySet();
		
		test.testRemove();
		test.testEntrySet();
		
		test.testModify();
		test.testEntrySet();
	}

}

8.StudentComparator

package com.imocc.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {

	@Override
	public int compare(Student o1, Student o2) {
		// TODO Auto-generated method stub
		return o1.name.compareTo(o2.name);
	}

}


9.CollectionsTest

package com.imocc.collection;

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



public class CollectionsTest {
	/**
	 * Interger泛型排序
	 */
	public void testSort1(){
		List<Integer> list=new ArrayList(10);
		Random random=new Random();
		Integer k;
		System.out.println("成功添加整数:");
		for(int i=0;i<10;i++){
			do{
				k=random.nextInt(100);
			}while(list.contains(k));
			list.add(k);
			System.out.print( k +" ");
		}
		
		System.out.println("\n-------排序前------");
		for(Integer integer:list){
			System.out.print(integer+" ");
		}
		
		Collections.sort(list);
		System.out.println("\n-------排序后------");
		for(Integer integer:list){
			System.out.print(integer+" ");
		}
	}
	
	/**
	 * String泛型排序
	 */
	public void testSort2(){
		List<String> list=new ArrayList(10);
		String base = "abcdefghijklmnopqrstuvwxyz0123456789"; //生成字符串从此序列中取
		Random random=new Random();
	
		System.out.println("成功添加整数:");
		for(int i=0;i<10;i++){
			StringBuffer sb = new StringBuffer(); 
			do{
				 int num=random.nextInt(base.length());
				 for(int j = 0 ; j < num; ++j){  
		            int number = random.nextInt(base.length());//[0,62)
		            sb.append(base.charAt(number));  
		        }  
			}while(list.contains(sb));
			list.add(sb.toString());
			System.out.print( sb +" ");
		}
		System.out.println("\n-------排序前------");
		for(String str:list){
			System.out.print(str+" ");
		}
		
		Collections.sort(list);
		System.out.println("\n-------排序后------");
		for(String str:list){
			System.out.print(str+" ");
		}
	}
	/**
<span style="white-space:pre">	</span> * Interger泛型排序
<span style="white-space:pre">	</span> */
<span style="white-space:pre">	</span>public void testSort3(){
<span style="white-space:pre">		</span>List<Student> studentList=new ArrayList<Student>();
<span style="white-space:pre">		</span>studentList.add(new Student(10000+"","小黑"));
<span style="white-space:pre">		</span>studentList.add(new Student(233+"","小明"));
<span style="white-space:pre">		</span>studentList.add(new Student(68+"","小红"));
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>System.out.println("\n-------排序前------");
<span style="white-space:pre">		</span>for(Student str:studentList){
<span style="white-space:pre">			</span>System.out.print(str.id+" ");
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>Collections.sort(studentList);
<span style="white-space:pre">		</span>System.out.println("\n-------排序后------");
<span style="white-space:pre">		</span>for(Student str:studentList){
<span style="white-space:pre">			</span>System.out.print(str.id+" ");
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>Collections.sort(studentList,new StudentComparator());
<span style="white-space:pre">		</span>System.out.println("\n-------按照姓名排序后------");
<span style="white-space:pre">		</span>for(Student str:studentList){
<span style="white-space:pre">			</span>System.out.print(str.id+" ");
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CollectionsTest test=new CollectionsTest ();
		test.testSort1();
		test.testSort2();
	}

}





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:59338次
    • 积分:2335
    • 等级:
    • 排名:第16027名
    • 原创:172篇
    • 转载:62篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论