boolean run = true;
while(true)
{
System.out.println("Enter A to add, S to search, E to exit");
String temp = input.next();
switch(temp)
{
case "A":
case "a":
System.out.println("Please enter the building name: ");
newClassroom.setBuildingName(input.next());
System.out.println("Please enter the room number: ");
newClassroom.setRoomNumber(input.next());
System.out.println("Please enter the capacity: ");
newClassroom.setCapacity(input.nextInt());
System.out.println("Please enter the academic department: ");
newClassroom.setAcadDept(input.next());
System.out.println("Please enter whether or not the room has a projector: ");
newClassroom.setProjector(input.nextBoolean());
List.add(newClassroom);
break;
case "S":
case "s":
System.out.println("Enter the building name and room number you wish to locate");
//String buildingSearch = input.next();
//int roomSearch = input.nextInt();
System.out.println(List);
//System.out.println(buildingSearch + roomSearch);
Classroom temporary = new Classroom();
temporary.setBuildingName(input.next());
temporary.setRoomNumber(input.next());
break;
case "E":
case "e":
System.exit(0);
}
}
}
我正在尝试检查并查看ArrayList中是否包含对象。我尝试过使用contains,但有人说我应该尝试使用.equals()代替。
答案 0 :(得分:0)
两者都是必需的。您必须覆盖equals()
类中的ClassRoom
方法,该方法与其他ClassRoom
对象进行比较,例如房间号(取决于您将如何实现它)。
现在,当调用contains()
方法时,它将通过调用ClassRoom
方法并比较Room no来检查每个equals()
对象。如果它已经存在,它将返回true。
class ClassRoom {
int roomNo;
public ClassRoom(int r) {
// TODO Auto-generated constructor stub
this.roomNo = r;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
ClassRoom cr = (ClassRoom)obj;
return this.roomNo == cr.roomNo;
}
}
class TestContains {
public static void main(String[] args) {
ClassRoom c1 = new ClassRoom(5);
ClassRoom c2 = new ClassRoom(6);
ClassRoom c3 = new ClassRoom(7);
List<ClassRoom> list = new ArrayList<ClassRoom>();
list.add(c1);
list.add(c2);
list.add(c3);
ClassRoom c8 = new ClassRoom(8);
ClassRoom c7 = new ClassRoom(7);
System.out.println(list.contains(c8));
System.out.println(list.contains(c7));
}
}
输出:
假
真