我所有的代码基本和老师的都一样,唯一不同就是Course类采用的是get()和set()方法,访问Course的成员变量,为什么结果和老师不一样呢,输入的课程明明存在,却显示false,能有人给解答一下吗?谢谢。
public class Course {
private String id,name;
public Course(String id,String name){
this.id=id;
this.name=name;
}
public Course() {
// TODO Auto-generated constructor stub
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
我也是用封装的set和get,重写后结果也是false,不知道是还不是还要重写hashCode?????????
输出的结果是:
成功添加了课程1:java
成功添加了课程2:c语言
成功添加了两门课程:3:大学英语4:php
成功添加了两门课程:5:商务英语6:大学物理
备选课程里是否存在课程:c语言,false
备选课程里是否存在课程:c语言,false
备选课程里是否存在课程:c语言,false
public class ListTest {
public List<Course> courseToSelect;
private Scanner input=new Scanner(System.in);
public ListTest(){
this.courseToSelect=new ArrayList<Course>();
}
public void listAdd(){
Course c1=new Course("1","java");
courseToSelect.add(c1);
Course temp=(Course)courseToSelect.get(0);
System.out.println("成功添加了课程"+temp.getId()+":"+temp.getName());
Course c2=new Course("2","c语言");
courseToSelect.add(0, c2);
Course temp1=(Course)courseToSelect.get(0);
System.out.println("成功添加了课程"+temp1.getId()+":"+temp1.getName());
Course [] c3={new Course("3","大学英语"),new Course("4","php")};
courseToSelect.addAll(Arrays.asList(c3));
Course temp2=(Course)courseToSelect.get(2);
Course temp3=(Course)courseToSelect.get(3);
System.out.println("成功添加了两门课程:"+temp2.getId()+":"+temp2.getName()+
temp3.getId()+":"+temp3.getName());
Course [] c4={new Course("5","商务英语"),new Course("6","大学物理")};
courseToSelect.addAll(2, Arrays.asList(c4));
Course temp4=(Course)courseToSelect.get(2);
Course temp5=(Course)courseToSelect.get(3);
System.out.println("成功添加了两门课程:"+temp4.getId()+":"+temp4.getName()+
temp5.getId()+":"+temp5.getName());
}
public void testContains(){
Course cr= courseToSelect.get(0);
System.out.println("备选课程里是否存在课程:"+cr.getName()+","
+courseToSelect.contains(cr.getName()));
Course coure2=new Course(cr.getId(),cr.getName());
System.out.println("备选课程里是否存在课程:"+coure2.getName()+","
+courseToSelect.contains(coure2.getName()));
}
public static void main(String[] agrs){
ListTest lt=new ListTest();
lt.listAdd();
lt.testContains();
}
代码,效果截图,报错信息