2017-04-22 143 views
0

在我們當前的章節中,我們使用的數組創建了一個列表,以便從另一個類中調用列表。從另一個類中顯示多個數組列表

目標:顯示來自另一個類的並行數組,這可以是單數或組。

問題:調用具有不同數據類型的多並行數組的最佳或有效方法?

錯誤:以非法聲明開始,如先前在此處指示的是整個代碼,請忽略我剛測試的循環顯示以確保陣列安裝正確。

謝謝大家,再一次的任何援助深表感謝

import java.util.ArrayList; 

public class Employee { 

    public static void main(String[] args) { 

// create an array with employee number, first name, last name, wage, and Skill 
     int[] empID = {1001, 1002, 1003}; 
     String[] firstName = {"Barry", "Bruce", "Selina"}; 
     String[] lastName = {"Allen", "Wayne", "Kyle"}; 
     double[] wage = {10.45, 22.50, 18.20}; 
     String[] skill = {"Delivery Specialist", "Crime Prevention", "Feline Therapist"}; 
     /* 
for (int i = 0; i < empID.length; i++) 
{ 
System.out.print("Employee ID: " + empID[i] + "\n"); 
System.out.print("First Name: " + firstName[i] + "\n"); 
System.out.print("Last Name: " + lastName[i] + "\n"); 
System.out.print("Hourly Wage: $" + wage[i] + "\n"); 
System.out.print("Skill: " +skill[i]); 
System.out.println("\n"); 
} 
     */ 
     //create an object to be called upon from another class 
public ArrayList<int, String, String, double, String> getEmployee() { 
     ArrayList<int, String, String, double, String> employeeList = new ArrayList<int, String, String, double, String>(); 
     employeeList.add(empID); 
     employeeList.add(firstName); 
     employeeList.add(lastName); 
     employeeList.add(wage); 
     employeeList.add(skill); 

     return employeeList; 
    } 

} 
} //end of class 
+1

ArrayLists只能有**一個**類型參數。我建議將員工班級分開並提供相應的屬性。 –

+0

哦所以使3顯示方法,字符串,詮釋,雙...有意義 – Elements

+0

@Ousmane該指示說建立一個類與陣列:僱員ID,第一,最後,工資,技能。建立另一個班級並顯示信息。 – Elements

回答

1

首先,你不能聲明這樣一個ArrayList:

ArrayList<int, String, String, double, String> 

如果你想,你可以創建自己的對象,創建一個可以取這些值的類,然後你可以創建一個這個對象的ArrayList例如:

class MyClass{ 
    int att1; 
    String att2; 
    String att3; 
    double att4; 
    String att5; 

    public MyClass(int att1, String att2, String att3, double att4, String att5) { 
     this.att1 = att1; 
     this.att2 = att2; 
     this.att3 = att3; 
     this.att4 = att4; 
     this.att5 = att5; 
    } 
} 

然後你可以這樣創建一個ArrayList:

List<MyClass> list = new ArrayList<>(); 
+2

@ Ousmane&@ YF非常感謝您,現在嘗試更改! – Elements

+0

歡迎您@Elements –

0

再回到Java基礎,它是一個面向對象的編程語言,所以你應該始終如果可能的目標是抽象的「東西」到一個對象。您應該將所有關於「僱員」的共同屬性封裝到一個類中,並將所有數據作爲字段。

如上面的答案所示,創建ArrayList<MyClass>是初始化arraylist的正確方法,因爲它們只能採用一種類型的數據。您可能已經看到其他課程採用多種類型,例如HashMap<Type1, Type2>,但這些課程是出於特定原因。確保首先檢查API文檔!