簡體   English   中英

java - 如何檢查是否存在具有某些值的實體java

[英]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 中的兩個方法:

  • 公共布爾等於(對象 obj)
  • 公共 int hashCode()

如果您希望使用 Client 對象作為 Map 中的鍵,您也應該這樣做。

請考慮以下兩個資源以獲取更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM