Link to home
Start Free TrialLog in
Avatar of ctoan
ctoan

asked on

Replicating an array in java

I would like to know of the most efficient way of doing the following. Please note, I know how this can be achieved by putting this in a for loop. However, if there is a more efficient way of doing it, I would like your recommendation.

Suppose I have an array of Strings:

String[] names = new String[] {"Alpha", "Beta", "Gamma"};

I would like to create a new array with the Strings in the original array replicated (repeated) multiple times.

Example:

String[] replicatedNames = new String[30];

{"Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma","Alpha", "Beta", "Gamma"};

I was hoping there would be a straightforward way of doing this with System.arraycopy(), but that does not seem to be the case.
Avatar of gnemi
gnemi
Flag of United States of America image

String[] replicate = ArrayUtils.addAll(names, names);
Avatar of ctoan
ctoan

ASKER

That would give me an array of 6 Strings. Not the solution that I am looking for.
One of the things that you could try is
String[] names = new String[] {"Alpha", "Beta", "Gamma"};

ArrayList<String> array = new ArrayList<String>();

//Repeat # of times required
for (i=0;i<10;i++){
         Collections.addAll(array , name);
}

String [] newNames = new String[array.size];
array.toArray(newNames);

Open in new window

SOLUTION
Avatar of gnemi
gnemi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:)