2017-05-23 15 views
1

我想在集合中存儲Employee_id (int)Employee_name (String) & Employee_Salary(long)。其中Employee_id應該始終是唯一的&按升序排序。 Employee_names可以重複。 請給我建議我可以使用哪個Java-Collection &這將是怎樣的基本程序?要存儲員工的詳細信息,可以使用哪些collection_type以下要求?

在此先感謝。

+3

您可以使用一個'TreeMap ',其中的關鍵是員工ID。 – Eran

+0

所以Employee對象將包含Employee_name和Employee_salary,是嗎? –

+0

是的,我還會在其中包含員工ID。 – Eran

回答

1

這裏使用一個TreeMap是一個例子:

JAVA

import java.util.TreeMap; 
import java.util.Set; 
import java.util.Iterator; 
import java.util.Map; 

... 

/* This is how to declare TreeMap */ 
    TreeMap<Integer, String> tmap = 
     new TreeMap<Integer, String>(); 

    /*Adding elements to TreeMap*/ 
    tmap.put(1, "Data1"); 
    tmap.put(23, "Data2"); 
    tmap.put(70, "Data3"); 
    tmap.put(4, "Data4"); 
    tmap.put(2, "Data5"); 

    /* Display content using Iterator*/ 
    Set set = tmap.entrySet(); 
    Iterator iterator = set.iterator(); 
    while(iterator.hasNext()) { 
    Map.Entry mentry = (Map.Entry)iterator.next(); 
    System.out.print("key is: "+ mentry.getKey() + " & Value is: "); 
    System.out.println(mentry.getValue()); 
    } 

您還可以使用HashMap(不排序應用)

+0

**排序**不適用於'HashMap'。 – Sergey

0

我會用HashMap存儲非重複EMPLOYEE_ID。 你需要兩個HashMap來存儲以下內容: EMPLOYEE_ID,Employee_Name,Employee_Salary

//this will hold the id and name 
HashMap<Integer, String> employeeHM = new HashMap<>(); 
//this will hold the id of employeeHM's HashMap and the salary 
HashMap<Integer, Long> salaryHM = new HashMap<>(); 

像@ThatAwesomeCoder說,HashMap中缺少排序。您可以通過創建一個循環來讀取employeeHM中的所有id並使用排序函數將其排序爲ArrayList集合來解決此問題。

+0

HashMap 也可以。 –

0

如果您需要將員工數據存儲爲鍵值對,則可以使用帶有EmployeeID的TreeMap作爲唯一鍵。如果你需要以集合的形式存儲它,那麼使用Treeset的接受比較器的重載構造函數怎麼樣?在比較器內部,您可以指定比較邏輯。只需我的兩分錢..

相關問題