前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java数组放入集合优化

Java数组放入集合优化

作者头像
Erwin
发布2019-12-31 12:21:50
6050
发布2019-12-31 12:21:50
举报
文章被收录于专栏:啸天"s blog啸天"s blog

首先我们来一个一般写法

代码语言:javascript
复制
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.

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

代码语言:javascript
复制
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.

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档