我如何在测试类中构建一个数组

时间:2009-09-30 13:31:21

标签: java arrays

public static void main(String[] args){
  Employee [] employeeList =
    {
    // build your list here
    };
}

我究竟如何构建我的数组。

数组只是在另一个类中定义的2个字符串。

class Employee 
{
    protected String name;
    protected String jobTitle;          

    Employee(String n, String title)
    {
        name = n;                    
        jobTitle = title;
    }
}

6 个答案:

答案 0 :(得分:5)

public static void main(String[] args){
    Employee[] employeeList = new Employee[] {
        new Employee("Name1", "Job1"),
        new Employee("Name2", "Job2"),
        new Employee("Name3", "Job3"),
        new Employee("Name4", "Job4")
    };
}

答案 1 :(得分:2)

你可以构建对象

Employee [] employeeList =
  {
    new Employee("David", "CEO"),
    new Employee("Mark", "CTO")
  };

或者您也可以执行以下操作:

Employee[] employeeList = new Employee[2];
employeeList[0] = new Employee("David", "CEO");
employeeList[1] = new Employee("Mark", CTO");

答案 2 :(得分:2)

呃,什么??

我假设您只想构建一个拥有员工的阵列? 这是一种方式:

Employee [] employeeList = {new Employee("name", "title"), new Employee("name", "title")};

答案 3 :(得分:1)

Employee s[] = new Employee[]
{
    new Employee("a","b"), 
    new Employee("1","2")
};

答案 4 :(得分:1)

如果您不知道数组的大小,可以使用ArrayList集合。

ArrayList<Employee> employeeList = new ArrayList<Employee>();

然后您可以随意添加任意数量的员工

employeeList.add(new Employee("a","b"));

可以通过类似于数组的索引访问员工

tempEmployee = employeeList.get(0);

这个类有很多其他有用的功能,只需要一个直的数组就会很困难。

API:http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html

答案 5 :(得分:0)

Employee EmployeeList[] = new Employee[10]; // Creates an array of 10 Employee objects

编辑,一个更完整的例子:

class Employee
{
   protected String name;
   protected String jobTitle;

   Employee(String n, String title)
   { 
      name = n;
      jobTitle = title;
   }

   public static void main(String[] args){
      Employee employeeList[] =new Employee[10];

      Employee a = new Employee("a", "b");

      employeeList[0] = a;

      System.out.printf("%s %s\n", employeeList[0].name, employeeList[0].jobTitle);

   }

}