8

How do I replace the following array with an ArrayList.

Employee[] companyTeam = {manager, engineer1, superviso1, accountant, intern };
Sameena
  • 93
  • 6

2 Answers2

4

You can do something like

List<Employee> companyTeam = Arrays.asList(manager, engineer1, superviso1, accountant, intern);
Mike B
  • 5,390
  • 2
  • 23
  • 45
  • Arrays.asList(companyTeam) in case you already have an array.. – TheLostMind Jan 23 '14 at 14:43
  • the word "Arrays" and "List" is highlighted in red. Any idea why? – Sameena Jan 23 '14 at 14:51
  • You need to import them. Add `import java.util.List;` and `import java.util.Arrays;` to the top of your file. Or if you're using Eclipse `ctrl + shift + O` will import them for you. – Mike B Jan 23 '14 at 14:57
  • Hi Mike, that works. Thanks. But if Im only to use the import java.util.ArrayList command. How would I go about writing the code for it? I tried using ArrayList companyTeam = {manager, engineer1, superviso1, accountant, intern};but then im getting an "illegal initializer for for ArrayList error" – Sameena Jan 23 '14 at 15:16
  • You can do `ArrayList companyTeam = new ArrayList(Arrays.asList(manager, engineer1, superviso1, accountant, intern));` – Mike B Jan 23 '14 at 15:29
0
 Employee[] companyTeam = {manager, engineer1, superviso1, accountant, intern };
 List<Employee>  list=Arrays.asList(companyTeam);// array to List

You already have an array, So you can use Arrays.asList(companyTeam) to convert array to List

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115