如何在Java中重复数组的元素?

例如,给定数组{a,b,c,d,e,f}和数字n,我想生成一个类似于n{a,b,c,d,e,f,a,b,c,d,e,f,a,b,c,...} -element数组。

如果我事先知道输入和输出数组的长度,则可以这样写:

int a=input[0], b=input[1], c=input[2], d=input[3], e=input[4], f=input[5];

int[] array = new int[n];
array[0]=a; array[1]=b; array[2]=c; array[3]=d; array[4]=e; array[5]=f;
array[6]=a; array[7]=b; array[8]=c; array[9]=d; array[10]=e; array[11]=f;
array[12]=a; array[13]=b; array[14]=c; // .. and so on

但是,如果我还不知道长度,该怎么办?我想我必须使用某种循环,但是我不确定如何编写一个循环。还是像某些其他语言一样,是否有一些内置的方法可以重复使用Java中的数组?

最佳答案

此实现比此处显示的其他实现更简洁,更快捷。

public static <T> T[] repeat(T[] arr, int newLength) {
    T[] dup = Arrays.copyOf(arr, newLength);
    for (int last = arr.length; last != 0 && last < newLength; last <<= 1) {
        System.arraycopy(dup, 0, dup, last, Math.min(last << 1, newLength) - last);
    }
    return dup;
}

理论
System.arraycopy是本地调用。因此,它非常快,但这并不意味着它是最快的方法。

每隔一个解决方案都会逐个元素复制数组。我的解决方案复制较大的块。每次迭代都会复制数组中的现有元素,这意味着循环最多将运行 log2(n)次。

分析报告

这是我的基准代码以重现结果:
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;

@Fork(3)
@BenchmarkMode(Mode.AverageTime)
@Measurement(iterations = 10, timeUnit = TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
@Threads(1)
@Warmup(iterations = 5, timeUnit = TimeUnit.NANOSECONDS)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {

  private static final String[] TEST_ARRAY = { "a", "b", "c", "d", "e", "f" };
  private static final int NEW_LENGTH = 10_000;

  @Benchmark
  public String[] testMethod() {
    String[] dup = Arrays.copyOf(TEST_ARRAY, NEW_LENGTH);
    for (int last = TEST_ARRAY.length; last != 0 && last < NEW_LENGTH; last <<= 1) {
      System.arraycopy(dup, 0, dup, last, Math.min(last << 1, NEW_LENGTH) - last);
    }
    return dup;
  }

  @Benchmark
  public String[] testMethod1() {
    String[] arr = new String[NEW_LENGTH];
    for (int i = 0; i < NEW_LENGTH; i++) {
      arr[i] = TEST_ARRAY[i % TEST_ARRAY.length];
    }
    return arr;
  }

  @Benchmark
  public String[] testMethod2() {
    List<String> initialLetters = Arrays.asList(TEST_ARRAY);
    List<String> results = new ArrayList<>();
    int indexOfLetterToAdd = 0;
    for (int i = 0; i < 10000; i++) {
      results.add(initialLetters.get(indexOfLetterToAdd++));
      if (indexOfLetterToAdd == initialLetters.size()) {
        indexOfLetterToAdd = 0;
      }
    }
    return results.toArray(new String[results.size()]);
  }

  @Benchmark
  public String[] testMethod3() {
    String result[] = new String[NEW_LENGTH];
    for (int i = 0, j = 0; i < NEW_LENGTH && j < TEST_ARRAY.length; i++, j++) {
      result[i] = TEST_ARRAY[j];
      if (j == TEST_ARRAY.length - 1) {
        j = -1;
      }
    }
    return result;
  }

  @Benchmark
  public String[] testMethod4() {
    String[] result = Stream.iterate(TEST_ARRAY, x -> x).flatMap(x -> Stream.of(TEST_ARRAY)).limit(NEW_LENGTH)
        .toArray(String[]::new);
    return result;
  }
}

结果
Benchmark                Mode  Cnt      Score      Error  Units
MyBenchmark.testMethod   avgt   30   4154,553 ±   11,242  ns/op
MyBenchmark.testMethod1  avgt   30  19273,717 ±  235,547  ns/op
MyBenchmark.testMethod2  avgt   30  71079,139 ± 2686,136  ns/op
MyBenchmark.testMethod3  avgt   30  18307,368 ±  202,520  ns/op
MyBenchmark.testMethod4  avgt   30  68898,278 ± 2488,104  ns/op

编辑

我改掉了这个问题,并按照建议的更精确的基准回答了这个问题。
Fastest way to create new array with length N and fill it by repeating a given array

关于java - 重复数组的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32305652/

10-11 01:22
查看更多