• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 317
  • Last Modified:

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.
0
ctoan
Asked:
ctoan
2 Solutions
 
gnemiCommented:
String[] replicate = ArrayUtils.addAll(names, names);
0
 
ctoanAuthor Commented:
That would give me an array of 6 Strings. Not the solution that I am looking for.
0
 
anilallewarCommented:
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

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
gnemiCommented:
That would give me an array of 6 Strings. Not the solution that I am looking for.
You would need to repeatedly call it to do more. That is the only option I'm aware of without using a loop.
0
 
CEHJCommented:
I was hoping there would be a straightforward way of doing this with System.arraycopy(), but that does not seem to be the case.

That is the most efficient way of doing it, rather than creating a Collection and then turning it into an array, but of course you do need a loop
0
 
CEHJCommented:
:)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now