OVERTONE
OVERTONE

Reputation: 12187

how do i build an array in the test class

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

how exactly do I build my array.

the array is just 2 strings that are defined in another class.

class Employee 
{
    protected String name;
    protected String jobTitle;          

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

Upvotes: 1

Views: 3023

Answers (6)

Omry Yadan
Omry Yadan

Reputation: 33616

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

Upvotes: 1

FModa3
FModa3

Reputation: 15019

If you don't know the size of the array ahead of time, you could use the ArrayList collection.

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

Then you can add as many Employees as you want as you go

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

The employees can be accessed by index similar to an array

tempEmployee = employeeList.get(0);

This class has a lot of other useful functions that would be otherwise difficult with just a straight array.

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

Upvotes: 1

nkr1pt
nkr1pt

Reputation: 4666

errm, what??

I assume you simply want to build an array that holds employees? This is one way:

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

Upvotes: 2

notnoop
notnoop

Reputation: 59299

You can just construct the objects

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

Or you can also do the following:

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

Upvotes: 2

NawaMan
NawaMan

Reputation: 25687

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")
    };
}

Upvotes: 5

poundifdef
poundifdef

Reputation: 19353

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

edit, a more complete example:

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);

   }

}

Upvotes: 0

Related Questions