java 数组优化_Java数组放入集合优化

这篇文章上次修改于 422 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

首先我们来一个一般写法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.

然后我就按照他的这个优化了一下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是不会进入的,规则仅检测最惯用的模式,不会考虑具有非平凡控制流的循环。 例如,有条件复制的数组元素将被忽略。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值