10
2020
01

Java数组放入集合优化

首先我们来一个一般写法

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
  }

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

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

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.
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是不会进入的,规则仅检测最惯用的模式,不会考虑具有非平凡控制流的循环。 例如,有条件复制的数组元素将被忽略。

本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。

微信扫码关注

更新实时通知

« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。