跟着老师上课讲的敲得。。。
ChildCourse.java
package com.imooc.collection;
public class ChildCourse extends Course {
}
CollectionsTest.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* 将要完成:
* 1.通过Collections.sort()方法,对Integer泛型的List进行排序;
* 2.对String泛型的List进行排序;
* 3.对其他类型泛型的List进行排序,以Student为例。
* @author zhaoxin
*
*/
public class CollectionsTest {
/**
* 1.通过Collections.sort()方法,对Integer泛型的List进行排序;
* 创建一个Integer泛型的List,插入十个100以内的不重复随机整数,
* 调用Collections.sort()方法对其进行排序
*/
public void testSort1(){
List<Integer> integerList = new ArrayList<Integer>();
//插入十个100以内的不重复随机整数
Random random = new Random();
Integer k;
for(int i=0;i<10;i++){
do{
k = random.nextInt(100);
}while(integerList.contains(k));
integerList.add(k);
System.out.println("成功添加整数:"+k);
}
System.out.println("----------排序前-----------");
for (Integer integer : integerList) {
System.out.println("元素:"+integer);
}
Collections.sort(integerList);
System.out.println("----------排序后-----------");
for (Integer integer : integerList) {
System.out.println("元素:"+integer);
}
}
/**
* 2.对String泛型的List进行排序;
* 创建String泛型的List,添加三个乱序的String元素,
* 调用sort方法,再次输出排序后的顺序
*/
public void testSort2(){
List<String> stringList = new ArrayList<String>();
stringList.add("microsoft");
stringList.add("google");
stringList.add("lenovo");
System.out.println("----------排序前-----------");
for (String string : stringList) {
System.out.println("元素:"+string);
}
Collections.sort(stringList);
System.out.println("----------排序后-----------");
for (String string : stringList) {
System.out.println("元素:"+string);
}
}
/**
* 2.1 对String泛型的List进行排序(版本2)
* 1)创建完List<String>之后,往其中添加十条随机字符串
* 2)每条字符串的长度为10以内的随机整数
* 3)每条字符串的每个字符都为随机生成的字符,字符可以重复
* 4)每条随机字符串不可重复
*/
public void testSort3(){
List<String> stringList = new ArrayList<String>();
String str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
Random rd = new Random();
for(int i=0;i<10;i++){
//为了每次循环将string builder清空,所以创建对象在循环里
StringBuilder sb = new StringBuilder();
//nextInt(n),[0,n) 这里不考虑空串,所以r最小为1,故r如下
int r = rd.nextInt(10)+1;
do{
for(int j=0;j<r;j++){
sb.append(str.charAt(rd.nextInt(str.length())));
}
}while(stringList.contains(sb.toString()));
stringList.add(sb.toString());
System.out.println("成功添加字符串:"+sb.toString());
}
System.out.println("----------排序前-----------");
for (String string : stringList) {
System.out.println("字符串:"+string);
}
Collections.sort(stringList);
System.out.println("----------排序后-----------");
for (String string : stringList) {
System.out.println("字符串:"+string);
}
}
/**
* 3.对其他类型泛型的List进行排序,以Student为例。
*/
public void testSort4(){
List<Student> studentList = new ArrayList<Student>();
Random random = new Random();
studentList.add(new Student(random.nextInt(1000)+"","Mike"));
studentList.add(new Student(random.nextInt(1000)+"","Angela"));
studentList.add(new Student(random.nextInt(1000)+"","Lucy"));
studentList.add(new Student(10000+"","Beyonce"));
System.out.println("----------排序前-----------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
Collections.sort(studentList);
System.out.println("----------排序后-----------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
Collections.sort(studentList,new StudentComparator());
System.out.println("----------按照姓名排序后-----------");
for (Student student : studentList) {
System.out.println("学生:"+student.id+":"+student.name);
}
}
/**
*
* @param args
*/
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
// ct.testSort1();
// ct.testSort2();
// ct.testSort3();
ct.testSort4();
}
}
Course.java
package com.imooc.collection;
/**
* 课程类
* @author zhaoxin
*
*/
public class Course {
public String id;
public String name;
public Course(String id,String name){
this.id = id;
this.name = name;
}
public 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 (getClass() != obj.getClass())
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;
}
}
ListTest.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* 备选课程类
* @author zhaoxin
*
*/
public class ListTest {
/**
* 用于存放备选课程的list
*/
public List coursesToSelect;
public ListTest(){
this.coursesToSelect = new ArrayList();
}
/**
* 用于往coursesToSelect中添加备选课程
*/
public void testAdd(){
//创建一个课程对象,并通过调用add方法,添加到备选课程List中
Course cr1 = new Course("1","数据结构");
coursesToSelect.add(cr1);
Course temp = (Course) coursesToSelect.get(0);
System.out.println("添加了课程"+temp.id+":"+temp.name);
Course cr2 = new Course("2","C语言");
coursesToSelect.add(0,cr2);
Course temp2 = (Course) coursesToSelect.get(0);
System.out.println("添加了课程"+temp2.id+":"+temp2.name);
coursesToSelect.add(cr1);
Course temp0 = (Course) coursesToSelect.get(2);
System.out.println("添加了课程"+temp.id+":"+temp.name);
//一下方法会抛出数组下标越界异常
// Course cr3 = new Course("3","test");
// coursesToSelect.add(4,cr3);
//
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3 = (Course) coursesToSelect.get(3);
Course temp4 = (Course) coursesToSelect.get(4);
System.out.println("添加了两门课程"+temp3.id+":"+
temp3.name +";" + temp4.id +":" +temp4.name);
Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
Course temp5 = (Course) coursesToSelect.get(2);
Course temp6 = (Course) coursesToSelect.get(3);
System.out.println("添加了两门课程"+temp5.id+":"+
temp5.name+";"+temp6.id+":"+temp6.name);
}
/**
* 取得List中的元素的方法
* @param args
*/
public void testGet(){
int size = coursesToSelect.size();
System.out.println("有如下的课程待选:");
for(int i=0;i<size;i++){
Course cr = (Course) coursesToSelect.get(i);
System.out.println("课程:"+cr.id+":"+cr.name);
}
}
/**
* 通过迭代器来遍历List
* @param args
*/
public void testIterator(){
//通过集合的iterator方法,取得迭代器的实例
Iterator it = coursesToSelect.iterator();
System.out.println("有如下的课程待选(通过迭代器访问):");
while(it.hasNext()){
Course cr = (Course) it.next();
System.out.println("课程:"+cr.id+":"+cr.name);
}
}
/**
* 通过foreach方法访问集合元素
* @param args
*/
public void testForEach(){
System.out.println("有如下的课程待选(通过foreach访问):");
for(Object obj:coursesToSelect){
Course cr = (Course) obj;
System.out.println("课程:"+cr.id+":"+cr.name);
}
}
/**
* 修改List中的元素
* @param args
*/
public void testModify(){
coursesToSelect.set(4, new Course("7","毛概"));
}
/**
* 删除List中的元素
* @param args
*/
public void testRemove(){
// Course cr = (Course) coursesToSelect.get(4);
// System.out.println("我是课程:"+cr.id+";"+cr.name+",我即将被删除");
// coursesToSelect.remove(cr);
// System.out.println("即将删除4位置上的课程!");
// coursesToSelect.remove(4);
System.out.println("即将删除4位置和5位置上的课程!");
Course[] courses ={(Course) coursesToSelect.get(4),(Course) coursesToSelect.get(5)};
coursesToSelect.removeAll(Arrays.asList(courses));
System.out.println("成功删除课程!");
testForEach();
}
/**
* 往List中添加一些奇怪的东西
* @param args
*/
public void testType(){
System.out.println("能否往List中添加一些奇怪的东西呢??");
coursesToSelect.add("我不是课程,我只是一个无辜的字符串!!");
}
public static void main(String[] args){
ListTest lt = new ListTest();
lt.testAdd();
lt.testType();
lt.testForEach();
// lt.testGet();
// lt.testIterator();
// lt.testForEach();
// lt.testModify();
// lt.testForEach();
// lt.testRemove();
}
}
MapTest.java
package com.imooc.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;
/**
* 在构造器中初始化students属性
*/
public MapTest(){
this.students = new HashMap<String,Student>();
}
/**
* 测试添加:输入学生ID,判断是否被占用
* 若未被占用,则输入姓名,创建新学生对象,并且
* 添加到students中
*/
public void testPut(){
//创建一个Scanner对象,用来获取输入的学生ID和姓名
Scanner console = new Scanner(System.in);
int i = 0;
while(i<3){
System.out.println("请输入学生ID:");
String ID = console.next();
//判断该ID是否被占用
Student st = students.get(ID);
if(st == null){
//提示输入学生姓名
System.out.println("请输入学生姓名:");
String name = console.next();
//创建新的学生对象
Student newStudent = new Student(ID, name);
//通过调用students的put方法,添加ID—学生映射
students.put(ID, newStudent);
System.out.println("成功添加学生:"+students.get(ID).name);
i++;
}else{
System.out.println("该学生ID已被占用");
continue;
}
}
}
/**
* 测试Map的KeySet方法
*/
public void testKeySet(){
//通过KeySet方法,返回Map中的所有“键”的Set集合
Set<String> KeySet = students.keySet();
//取得student的容量
System.out.println("总共有:"+students.size()+"个学生!");
//遍历KeySet,取得每一个键,再调用get方法取得每个键对应的value
for (String stuId : KeySet) {
Student st = students.get(stuId);
if(st!=null)
System.out.println("学生:"+st.name);
}
}
/**
* 测试删除Map中的映射
*/
public void testRemove(){
//获取从键盘输入的待删除学生ID字符串
Scanner console = new Scanner(System.in);
while(true){
//提示输入待删除的学生ID
System.out.println("请输入要删除的学生ID!");
String ID = console.next();
//判断该ID是否有对应的学生对象
Student st = students.get(ID);
if(st==null){
//提示输入的ID并不存在
System.out.println("该ID不存在!");
continue;
}
students.remove(ID);
System.out.println("成功删除学生:"+st.name);
break;
}
}
/**
* 通过entrySet
*/
public void testEntrySet(){
//通过entrySet方法,返回Map中的所有键值对
Set<Map.Entry<String,Student>> entrySet = students.entrySet();
for (Entry<String, Student> entry : entrySet) {
System.out.println("取得键:"+entry.getKey());
System.out.println("对应的值为:"+entry.getValue().name);
}
}
/**
* 利用put方法修改Map中已有映射
*/
public void testModify(){
//提示输入要修改的学生ID
System.out.println("请输入要修改的学生ID");
//创建一个Scanner对象,去获取从键盘上输入的学生ID字符串
Scanner console = new Scanner(System.in);
while(true){
//获取从键盘输入的学生ID
String stuID = console.next();
//从students中查找该学生ID对应的学生对象
Student student = students.get(stuID);
if(student==null){
System.out.println("该ID不存在,请重新输入!");
continue;
}
//提示当前对应的学生对象的姓名
System.out.println("当前该学生ID,所对应的学生为:"+student.name);
//提示输入新的学生姓名,来修改已有的映射
System.out.println("请输入新的学生姓名:");
String name = console.next();
Student newStudent = new Student(stuID,name);
students.put(stuID, newStudent);
System.out.println("修改成功!");
break;
}
}
/**
* 测试Map中,是否包含某个Key值或者某个Value值
*/
public void testContainsKeyOrValue(){
//提示用户输入学生id
System.out.println("请输入要查询的学生ID:");
Scanner console = new Scanner(System.in);
String id = console.next();
//再Map中,用containsKey()方法,来判断是否包含某个Key值
System.out.println("您输入的学生ID为:"+id+",在学生映射表中是否存在:"+
students.containsKey(id));
if(students.containsKey(id))
System.out.println("对应的学生为:"+students.get(id).name);
//提示输入学生姓名
System.out.println("请输入要查询的学生姓名:");
String name = console.next();
//用containsValue()方法,来判断是否包含某个Value值
if(students.containsValue(new Student(null,name)))
System.out.println("在学生映射表中,确实包含学生:"+name);
else
System.out.println("在学生映射表中不存在该学生!");
}
/**
*
* @param args
*/
public static void main(String[] args){
MapTest mt = new MapTest();
mt.testPut();
mt.testKeySet();
// mt.testRemove();
// mt.testEntrySet();
// mt.testModify();
// mt.testEntrySet();
mt.testContainsKeyOrValue();
}
}
SetTest.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
public List<Course> coursesToSelect;
private Scanner console;
public Student student;
public SetTest(){
coursesToSelect = new ArrayList<Course>();
console = new Scanner(System.in);
}
public void testAdd(){
//创建一个课程对象,并通过调用add方法,添加到备选课程List中
Course cr1 = new Course("1","数据结构");
coursesToSelect.add(cr1);
Course cr2 = new Course("2","C语言");
coursesToSelect.add(0,cr2);
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
}
/**
* 通过foreach方法访问集合元素
* @param args
*/
public void testForEach(){
System.out.println("有如下的课程待选(通过foreach访问):");
for(Object obj:coursesToSelect){
Course cr = (Course) obj;
System.out.println("课程:"+cr.id+":"+cr.name);
}
}
/**
* 测试List的contains方法
*/
public void testListContains(){
//取得备选课程序列的第0个元素
Course course = coursesToSelect.get(0);
//打印输出coursesToSelect是否包含course对象
System.out.println("取得课程:"+course.name);
System.out.println("备选课程中是否包含课程:"+course.name+","+
coursesToSelect.contains(course));
//提示输入课程名称
System.out.println("请输入课程名称:");
String name = console.next();
//新创建一个课程对象,ID和名称,与course对象完全一样
Course course2 = new Course();
course2.name = name;
System.out.println("新创建课程:"+course2.name);
System.out.println("备选课程中是否包含课程:"+course2.name+","+
coursesToSelect.contains(course2));
}
//创建学生对象并选课
public void createStudentAndSelectCours(){
//创建一个学生对象
student = new Student("1","小明");
System.out.println("欢迎学生:"+student.name+"选课!");
//创建一个Scanner对象,用来接收从键盘输入的课程ID
Scanner console = new Scanner(System.in);
for(int i = 0;i<3;i++){
System.out.println("请输入课程ID");
String courseId = console.next();
for (Course cr : coursesToSelect) {
if(cr.id.equals(courseId)){
student.courses.add(cr);
/**
* set中,添加某个对象,无论添加多少次,
* 最终只会保留一个该对象(的引用),
* 并且,保留的是第一次添加的那一个;
*/
// student.courses.add(cr);
}
}
}
}
/**
* 测试Set的contains方法
*/
public void testSetContains(){
//输入课程名称
System.out.println("请输入学生已选的课程名称:");
String name = console.next();
//新创建一个课程对象,ID和名称,与course对象完全一样
Course course2 = new Course();
course2.name = name;
System.out.println("新创建课程:"+course2.name);
System.out.println("备选课程中是否包含课程:"+course2.name+","+
student.courses.contains(course2));
//通过indexOf方法来取得某元素的索引位置
if(coursesToSelect.contains(course2))
System.out.println("课程"+course2.name+"的索引位置为:"+
coursesToSelect.indexOf(course2));
}
/**
*
* @param args
*/
public static void main(String[] args) {
SetTest st = new SetTest();
st.testAdd();
st.testListContains();
st.testForEach();
// st.createStudentAndSelectCours();
// st.testSetContains();
// st.testForEachForSet(student);
}
public void testForEachForSet(Student student){
//打印输出,学生所选的课程!
System.out.println("共选择了:"+student.courses.size()+"门课程!");
for (Course cr : student.courses) {
System.out.println("选择了课程:"+cr.id+":"+cr.name);
}
}
}
Student.java
package com.imooc.collection;
import java.util.HashSet;
import java.util.Set;
/**
* 学生类
* @author zhaoxin
*
*/
public class Student implements Comparable<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>();
}
@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 (getClass() != obj.getClass())
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);
}
}
StudentComparator.java
package com.imooc.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);
}
}
TestGeneric.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.List;
public class TestGeneric {
/**
* 带有泛型——Course,的List类型属性
*/
public List<Course> courses;
public TestGeneric(){
this.courses = new ArrayList<Course>();
}
/**
* 测试添加
*/
public void testAdd(){
Course cr1 = new Course("1","大学语文");
courses.add(cr1);
//泛型集合中,不能添加泛型规定的类型及其子类型以外的对象,否则会报错!
// courses.add("能否添加一些奇怪的东西呢??");
Course cr2 = new Course("2","Java基础");
courses.add(cr2);
}
/**
* 测试循环遍历
*/
public void testForEach(){
for(Course cr:courses){
System.out.println(cr.id+":"+cr.name);
}
}
/**
* 泛型集合可以添加泛型的子类型的对象实例
*/
public void testChild(){
ChildCourse ccr = new ChildCourse();
ccr.id = "3";
ccr.name = "我是子类型的课程对象实例~.~";
courses.add(ccr);
}
/**
* 泛型不能使用基本类型
*/
public void testBasicType(){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
System.out.println("基本类型必须使用包装类作为泛型!"+list.get(0));
}
/**
*
* @param args
*/
public static void main(String[] args) {
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testChild();
tg.testForEach();
tg.testBasicType();
}
}