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);??}/**測(cè)試add()、addAll()方法*/?public void testAdd() {//添加元素到末尾(默認(rèn))??Course cr1=new Course("S0041","數(shù)據(jù)結(jié)構(gòu)"); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //創(chuàng)建一個(gè)課程對(duì)象??coursesToSelect.add(cr1); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //通過(guò)調(diào)用add()方法,傳入課程實(shí)例到備選課程List中//添加元素到指定位置??Course cr2=new Course("C3256","C語(yǔ)言");??coursesToSelect.add(0, cr2);;???//批量添加??Course[] course= {new Course("L6693","離散數(shù)學(xué)"),new Course("H5567","匯編語(yǔ)言")};??coursesToSelect.addAll(Arrays.asList(course)); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //傳進(jìn)collection 的具體實(shí)例,將course數(shù)組轉(zhuǎn)換成List//在指定位置批量添加??Course[] course2= {new Course("G6698","高等數(shù)學(xué)"),new Course("D6631","大學(xué)英語(yǔ)")};??coursesToSelect.addAll(2,Arrays.asList(course2));??}/**測(cè)試ContainsAll( )方法*/public void testListContainsAll() {?? System.out.println("你要查詢多少個(gè)課程:"); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //運(yùn)行時(shí)賦值為2?? int num=console.nextInt();?? Course[] courses=new Course[num];?? System.out.println("請(qǐng)輸入你要查詢的課程的名稱:"); ? ? ? ? ? ? ? ? ? ?? //運(yùn)行時(shí)賦值為 ?數(shù)據(jù)結(jié)構(gòu) ??C語(yǔ)言?? 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))); ? ? ? ? ?? //結(jié)果運(yùn)行為false? ??????}
關(guān)于containsAll()方法的疑問(wèn):重寫(xiě)了Course的equals()方法,為什么輸出為false?
qq_A_229
2018-08-18 16:53:04