[英]How to check if exists entities with the some values java
我有两个实体 Client 和 Movie,我必须租电影,所以我需要一个客户和一部电影,这就是我创建类租赁的原因。 问题是当我想检查我想租电影时输入的 id 是否存在于客户端文件中时,如果不存在打印消息。但它不起作用。
类客户端:
public class Client extends BaseEntity<Long> {
private String name;
private int age;
public Client(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){return name;}
public int getAge(){return age;}
public void setName(String name){this.name=name;}
public void setAge(int age){this.age=age;}
@Override
public String toString(){
return "Client:{ " + name + " "+age + "} " + super.toString();
}
}
The Movie 和 client 几乎一样,Rental 类:
public class Rental extends BaseEntity<Long> {
private Long IdClient;
private Long IdMovie;
public Rental(Long IdClient,Long IdMovie){
this.IdClient = IdClient;
this.IdMovie = IdMovie;
}
public Long getIdClient() {return IdClient;}
public Long getIdMovie(){return IdMovie;}
public String toString(){
return "Rental:{ " + IdClient + " "+ IdMovie + "} " + super.toString();
}
}
和控制台,我尝试检查是否存在:
private Rental readRental(){
printAllClients();
printAllMovies();
System.out.println("Enter the Rentals ID , Clients ID and the rented Movie ID: ");
BufferedReader bufferR = new BufferedReader(new InputStreamReader(System.in));
try{
Long id=Long.valueOf(bufferR.readLine());
Long id1=Long.valueOf(bufferR.readLine());
Long id2=Long.valueOf(bufferR.readLine());
Rental rental = new Rental(id1, id2);
rental.setId(id);
return rental;
}catch (IOException e){
e.getStackTrace();
}
return null;
}
private void addRentals(){
Set<Client> clients = clientC.getAllClients();
Rental rental = readRental();
if (rental == null || rental.getId() < 0 ){
return;
}
if (!clients.contains(rental.getIdClient())){ //!!!!!!!!!!
System.out.println("Doesn't contains");
}
else{
System.out.println("Contains");
}
try{
rentalC.addRental(rental);
System.out.println("A rental was added.");
}
catch (ValidatorException e){
e.printStackTrace();
}
}
当我介绍一个存在的客户时,它给我“不存在”。 为什么?
您的客户端是一组客户端对象。 Rental.getIdClient() 返回一个 Long 对象。 一组客户端对象永远不能包含一个 Long(除非你破解了一些脏代码)。 建议:将您的客户端映射到 HashMap 而不是 Set:将客户端的 id 映射到客户端对象。
此外,在 Java 中,如果您希望在 Set 中使用 Client 对象,则类 Client 必须正确覆盖类 Object 中的两个方法:
如果您希望使用 Client 对象作为 Map 中的键,您也应该这样做。
请考虑以下两个资源以获取更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.