package com.imooc.collection;/** *Course类 */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 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; }}package com.imooc.collection;import java.util.*;/***SetTest类*/public static List<Course> coursesToSelect; private static Scanner console=new Scanner(System.in);public SetTest() { //初始化 coursesToSelect=new ArrayList<Course>(); console=new Scanner(System.in); }/**测试add()、addAll()方法*/ public void testAdd() {//添加元素到末尾(默认) Course cr1=new Course("S0041","数据结构"); //创建一个课程对象 coursesToSelect.add(cr1); //通过调用add()方法,传入课程实例到备选课程List中//添加元素到指定位置 Course cr2=new Course("C3256","C语言"); coursesToSelect.add(0, cr2);; //批量添加 Course[] course= {new Course("L6693","离散数学"),new Course("H5567","汇编语言")}; coursesToSelect.addAll(Arrays.asList(course)); //传进collection 的具体实例,将course数组转换成List//在指定位置批量添加 Course[] course2= {new Course("G6698","高等数学"),new Course("D6631","大学英语")}; coursesToSelect.addAll(2,Arrays.asList(course2)); }/**测试ContainsAll( )方法*/public void testListContainsAll() { System.out.println("你要查询多少个课程:"); //运行时赋值为2 int num=console.nextInt(); Course[] courses=new Course[num]; System.out.println("请输入你要查询的课程的名称:"); //运行时赋值为 数据结构 C语言 for(int i=0;i<num;i++) { System.out.print((i+1)+":"); String name=console.next(); try{ courses[i]=new Course(); }catch(NullPointerException e) { System.out.println("空指针异常!!"); } } System.out.println(coursesToSelect.containsAll(Arrays.asList(courses))); //结果运行为false ??????}
添加回答
举报
0/150
提交
取消