2017-10-05 32 views
-2

我有一個叫Employee的類,現在我想寫一個叫ReusaxCorp的類。該公司的每個員工都有一個ID,一個名字和一個工資總額,以後可以檢索。 ReusaxCorp類應註冊並刪除員工(從沒有員工開始)。我的問題是,我不知道我可以如何註冊員工並存儲他們。此外,我被告知使用多態性。下面是Employee類:Java「正在註冊」(存儲)並刪除「Employees」

public class Employee { 

    private String ID; 
    private String name; 
    private int grosssalary; 

    public Employee (String ID, String name, int grosssalary){ 
     this.ID = ID; 
     this.name = name; 
     this.grosssalary = grosssalary; 
    } 


    public int getGrosssalary() { 
     return grosssalary; 
    } 

    public void setGrosssalary(int grosssalary) { 
     this.grosssalary = grosssalary; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 
+0

這似乎是功課 – Ravi

+3

作業的問題都很好,但你必須表明你的ATT用你的問題解決問題。如果你完全迷失了,那麼你不應該在這裏發佈一個問題 - 你應該聯繫你的老師。 –

回答

-1

格里芬的答案有讓你開始的元素。 爲了詳細說明,您還應該確保Employee類正確地覆蓋方法equals()和hashCode(),以便您可以安全地使用List.remove(Object)方法。 例如,使用ID作爲唯一性的關鍵:

@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + ((ID == null) ? 0 : ID.hashCode()); 
    return result; 
} 


@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
      return true; 
    if (obj == null) 
      return false; 
    if (getClass() != obj.getClass()) 
      return false; 
    Employee other = (Employee) obj; 
    if (ID == null) { 
      if (other.ID != null) 
        return false; 
    } else if (!ID.equals(other.ID)) 
      return false; 
    return true; 
} 

現在可以解決這樣的事情在你的ReusaxCorp類:

private List<Employee> mEmployees = new ArrayList<Employee>() 

/** 
* Removes one employee from the corporation 
*/ 
public void remove(Employee employee) { 
    mEmployees.remove(employee); 
} 

/** 
* Inserts a new employee 
*/ 
public void insert(Employee employee) { 
    // can check for unicity (optional): 
    if (mEmployees.contains(employee)) throw new IllegalArgumentException("Employee already exists"); 

    mEmployees.add(employee); 
} 

如果你只知道你想要的員工的ID刪除,你可以創建一個新的Employee實例匹配現有的一個:

// Thanks to redefinition of equals(), it will match and remove the correct employee without having to know the name or salary. 
corp.remove(new Employee(ID, "", 0)); 
0

你的問題是相當廣泛然而生病看我能不能讓你開始...

你可以利用Employee對象的數組列表去「登記」的員工。

//create array list 
ArrayList<Employee> employees = new ArrayList<Employee>(); 

,如果你創建一個僱員現在...

//create employee (of course enter whatever you need for your constructor) 
Employee employee = new Employee("sampleID", "sampleName", 0); 

您可以將員工添加到數組列表。您還可以從特定索引的數組列表中刪除元素。下面是例子...

//add employee 
employees.add(employee); 
//remove employee(would have initialize int index to which you want to remove) 
employees.remove(int index); 

閱讀數組列表,看看你可以用他們做什麼。我確定他們有你在找什麼。