-4

how can I pass the Reference of an arraylist to an array?

I have an Arraylist but the method constraints that I should return an array and I should return an array with the same reference as the one given to me in the signature of the method, and I can not simply not use The ArrayList because that would require a lot of changes in the code. so is there a quick way to do it??

public Skill[] getSkills() {
  if (skills.size() == 0) {
    return null;
  }
  Skill[] result = new Skill[skills.size()];
  result = skills.toArray(result);
  return result;
}

public void setSkills(Skill[] skills) {
  if (skills.length != 0) {
    for (int i = 0; i < skills.length; i++) {
      this.skills.add(i, skills[i]);
    }
  }
}

the Junit test is:

@Test(timeout = 1000)
public void testGetSkills() {
  instance.setSkills(skills);
  assertSame("The returned skill array should be the same", instance.getSkills(), skills);
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Jane.
  • 13
  • 5

4 Answers4

2

how can I pass the Reference of an arraylist to an array?

public T[] method() {
List<T> list=....; 
 //other ops
return list.toArray(new T[list.size()]);
}

List#toArray(T..a) method acts as bridge between array-based and collection-based APIs.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

consider Ur method have parameter as follows

public Array method (Array signature)
{
ArrayList<object> ArrayList = new ArrayList<object>();

foreach(object test in ArrayList )
{
 if(test == signature)
{
    return test
}  
}
}

Thanks

Anand
  • 43
  • 5
0

I have an Arraylist but the method constraints that I should return an array

Can you not just do:

return list.toArray(new String[list.size()]);

Assuming your ArrayList is of Strings here of course - replace String with whatever type is relevant.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
0

you can return list.toArray( [list.size()]);

Civa
  • 2,058
  • 2
  • 18
  • 30