2017-04-22 137 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文档!