Java数组放入集合优化

首先我们来一个一般写法

1
2
3
4
5
6
7
8
9
10
11
12
public void makeCopies(String[] source) {

  this.array = new String[source.length];
  this.list = new ArrayList(source.length);

  for (int i = 0; i < source.length; i++) {
    this.array[i] = source[i]; // Noncompliant
  }

  for (String s : source) {
    this.list.add(s); // Noncompliant
  }

这个代码这样写是没有问题的,但是语句却很长,不易于阅读,网上查阅资料后发现这样一段话

Using a loop to copy an array or a subset of an array is simply wasted code when there are built-in functions to do it for you. Instead, use Arrays.copyOf to copy an entire array into another array, use System.arraycopy to copy only a subset of an array into another array, and use Arrays.asList to feed the constructor of a new list with an array.

Note that Arrays.asList simply puts a Collections wrapper around the original array, so further steps are required if a non-fixed-size List is desired.

然后我就按照他的这个优化了一下

1
2
3
4
public void makeCopies(String[] source) {
  this.array = Arrays.copyOf(source, source.length);
  Collections.addAll(this.list, source);
}

代码是不是简洁了许多呢?可是效果却是一摸一样的 注意 ,这样写有一个例外

Rule detects only the most idiomatic patterns, it will not consider loops with non-trivial control flow. For example, array elements that are copied conditionally are ignored.

1
2
3
4
5
6
7
8
9
public int[] getCopy(int[] source) {
  int[] dest = new int[source.length];
  for (int i = 0; i < source.length; i++) {
    if (source[i] > 10) {
      dest[i] = source[i];  // Compliant
    }
  }
  return dest;
}

他的意思是说如果用上面的方法,这个source[i] > 10是不会进入的,规则仅检测最惯用的模式,不会考虑具有非平凡控制流的循环。 例如,有条件复制的数组元素将被忽略。

坚持原创技术分享,您的支持将鼓励我继续创作!