mooc_java 集合框架下

1.判断List中课程是否存在

/**
     * 测试List的contains方法
     * @param args
     */
    public void testListContains(){
        Course course=(Course)coursesToSelect.get(0);
        System.out.println("取得课程"+course.name);
        System.out.println("备选课程中是否包含课程:"+course.name+","+coursesToSelect.contains(course));
        System.out.println("请输入课程名称:");
        String name=console.next();
        Course course2=new Course();
        course2.name=name;
        System.out.println("新加入:"+course2.name);
        System.out.println("备选课程中是否包含课程:"+course2.name+","+coursesToSelect.contains(course2));
    }
    

Course.java中重写equals

 1 public boolean equals(Object obj){
 2         if(this==obj)
 3             return true;
 4         if(obj==null)
 5             return false;
 6         if(!(obj instanceof Course))//判断是否为Course类型的对象
 7             return false;
 8         Course course=(Course) obj;
 9         if(this.name==null){
10             if(course.name==null)
11                 return true;
12             else
13                 return false;
14         }else{
15             if(this.name.equals(course.name))
16                 return true;
17             else {
18                 return false;
19             }
20                 
21         }
22     }

2.判断Set中课程是否存在

Set继承自Collection接口,所以也包含contains和containsAll方法

注意了这里关于使用 Set 集的 hashCode的方法,hashCode方法的工作原理是
Set.contains(E e)的时候,先调用从Object继承而来的hashCode方法,然后在调用equals()方法,连个方法都返回真的时候,才认定Set包含某个元素。jvm运行时,给每个对象分配唯一一个标志身份的标志hanshcode。众类鼻祖Object的hashCode()方法在默认情况下,判断哈希码是不是相同.即如同equals默认情况下比较的是二者是不是同一个内存快。Set集的contains方法,内部就是先调用hashCode再调用equals()方法。很多情况要结合实际对hashCode进行改写

3.获取List中课程的位置

indexOf()方法与lastIndexOf()方法实现原理:
1、遍历调用每个元素的equals()方法,如果返回true则将次元素的索引返回;
2、如果有多个相同元素,则只返回第一个元素的索引;
3、lastIndexOf()方法则从最后一个元素开始遍历;

1 if(coursesToSelect.contains(course2))
2             System.out.println("课程"+course2.name+"的索引位置为"+coursesToSelect.indexOf(course2));

4.判断Map中是否包含指定的key和value

Map映射表
一、判断是否包含某个Key值:containsKey()
二、判断是否包含某个Value值:containsValue()
1、同样是以每一个元素的value值的equals方法进行比较,所以需要重写value类的equals()方法来进行属性(某个)比较

 1 /**
 2      * 测试Map中是否包含某个Key值或某个Value值
 3      * @param args
 4      */
 5     public void testContainsKeyOrValue(){
 6         System.out.println("输入学生ID");
 7         Scanner console=new Scanner(System.in);
 8         String id=console.next();
 9         //在Map中,用containsKey方法判断是否包含某个Key值
10         System.out.println("您输入的学生ID"+id+",在映射表中是否存在"+students.containsKey(id));
11         if(students.containsKey(id))
12             System.out.println("对应的学生为 "+students.get(id).name);
13         System.out.println("请输入要查询的学生姓名");
14         String name=console.next();
15         //用containsValue方法,来判断是否包含某个Value值
16         if(students.containsValue(new Student(null, name)))
17             System.out.println("在学生映射表中确实存在"+name);
18         else 
19             System.out.println("不存在此学生");
20     }

因为Map的键值对应的值是唯一的,而值所映射的键值却有可能是多个的,而Contains方法自带的比较机制是比较索引,也就是地址,所以ContainsValue方法需要改写

在Student类中重写hashCode和equals方法

5.应用Collection.Sort()对List排序

字符串的排列顺序  数字:0-9大写字母:A-Z 小写字母:a-z

 1 /**
 2  * 通过Collection.sort()方法,对Integer泛型的List进行排序
 3  * 对String泛型的List进行排序
 4  * 对其他类型的List进行排序,例如Student
 5  */
 6 public class CollectionTest {
 7     public void testSort1(){
 8         List<Integer> integerList=new ArrayList<Integer>();
 9         //插入10个100以内的不重复随机数
10         Random r=new Random();
11         Integer k;
12         for(int i=0;i<10;i++){
13             do{
14                 k=r.nextInt(100);
15             }while(integerList.contains(k));
16             integerList.add(k);
17             System.out.println("添加数"+k);
18         }
19         System.out.println("--------------排序前-----------------");
20         for(Integer i:integerList){
21             System.out.println("元素"+i);
22         }
23         Collections.sort(integerList);
24         System.out.println("--------------排序后-----------------");
25         for(Integer i:integerList){
26             System.out.println("元素"+i);
27         }
28     }
29     /*
30      * 对S提让您更泛型的List排序
31      */
32     public void testSort2(){
33         List<String> stringList=new ArrayList<String>();
34         stringList.add("microsoft");
35         stringList.add("google");
36         stringList.add("Lenovo");
37         System.out.println("--------------排序前-----------------");
38         for(String s:stringList){
39             System.out.println("元素"+s);
40         }
41         Collections.sort(stringList);
42         System.out.println("--------------排序后-----------------");
43         for(String s:stringList){
44             System.out.println("元素"+s);
45         }
46     }
47     public static void main(String[] args) {
48         CollectionTest ct=new CollectionTest();
49         ct.testSort1();
50         ct.testSort2();
51     }
52 }
 1 //作业
 2 public void showStringSort(){
 3   //1.创建完List<String>之后,往其中添加十几条随机字符串
 4   List<String> strings = new ArrayList<String>();
 5   for(int i = 0;i<10;i++){
 6   String str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 7   Random random = new Random();
 8   StringBuffer sb = new StringBuffer();
 9   //长度10以内的随机数
10   int numLength = random.nextInt(9)+1;
11   for(int k = 0;k<numLength;k++){
12     //3.每条字符串的每个字符都为随机生成的字符,字符可以重复
13     int numIndex = random.nextInt(61);
14     sb.append(str.charAt(numIndex));
15   }
16   //判断生成的字符串是否已经被包含
17   if(!strings.contains(sb.toString())){
18     strings.add(sb.toString());
19   }else{
20     i--;
21   }
22 }
23 System.out.println("------排序前-------");
24 for(String str:strings){
25   System.out.println(str);
26 }
27 Collections.sort(strings);
28 System.out.println("------排序后-------");
29 for(String str:strings){
30   System.out.println(str);
31 }
32 }

6.对学生序列排序

 1 /*
 2      * 对其他类型泛型的List排序
 3      */
 4     public void testSort3(){
 5         List<Student> studentList=new ArrayList<Student>();
 6         studentList.add(new Student(1+"","小明"));
 7         studentList.add(new Student(2+"","小红"));
 8         studentList.add(new Student(3+"","小兰"));
 9         System.out.println("--------------排序前-----------------");
10         for(Student s:studentList){
11             System.out.println("元素"+s);
12         }
13         Collections.sort(studentList);//由于Student并不是Comparable接口的实现类,所以报错
14         System.out.println("--------------排序后-----------------");
15         for(Student s:studentList){
16             System.out.println("元素"+s);
17         }
18     }

7.Comparable & Comparator

Comparable接口是可比较的,可进行自然排序,其实现类需实现compareTo()方法,该方法返回值为正数时表示大于,负数表示小于,0表示等于。
Comparator接口是比较工具接口,用于定义临时比较规则,而不是默认比较规则,其实现需实现compare()方法。
java接口框架:Collection接口、Map接口、Collections工具类、Comparable接口、Comparator接口

8.实现学生序列排序

1 public class Student implements Comparable<Student>{
2 
3 @Override
4     public int compareTo(Student o) {         
5         return this.id.compareTo(o.id);
6     }
 1 public void testSort3(){
 2         List<Student> studentList=new ArrayList<Student>();
 3         Random r=new Random();
 4         studentList.add(new Student(r.nextInt(1000)+"","mike"));
 5         studentList.add(new Student(r.nextInt(1000)+"","angela"));
 6         studentList.add(new Student(r.nextInt(1000)+"","lucy"));
 7         System.out.println("--------------排序前-----------------");
 8         for(Student s:studentList){
 9             System.out.println("元素"+s.id+":"+s.name);
10         }
11         Collections.sort(studentList);
12         System.out.println("--------------排序后-----------------");
13         for(Student s:studentList){
14             System.out.println("元素"+s.id+":"+s.name);
15         }
16     }
1 System.out.println("--------------按照姓名排序后-----------------");
2         Collections.sort(studentList,new StudentComparator());
3         for(Student s:studentList){
4             System.out.println("元素"+s.id+":"+s.name);
5         }
在平凡中坚持前行,总有一天,会遇见优秀的自己
原文地址:https://www.cnblogs.com/mao-19/p/4985801.html