Initialize ArrayList with a range of integer values avoiding loops

问题: I would like to initialize an ArrayList with a range of integer values. This is what I want to avoid: ArrayList<Integer> numbers = new ArrayList<>(); for(int...

问题:

I would like to initialize an ArrayList with a range of integer values. This is what I want to avoid:

ArrayList<Integer> numbers = new ArrayList<>();
for(int i = 0; i < x; i++){
    numbers.add(i);
}

I found rangeClosed function for IntStream:

IntStream.rangeClosed(0, instance.getNumVertices()-1);

But I think that the conversiont to ArrayList won't be worth it.

I'm looking for efficiency...


回答1:

The ArrayList is backed by an array. If you want to fill it with ascending values, you won't get any quicker than just iterating over those values and adding them to the list.

The only thing I'd change in your example is initialize the array with the already known size, so that it wouldn't spend time and memory on expansion of the underlying array:

ArrayList<Integer> numbers = new ArrayList<>(x);
for(int i = 0; i < x; i++){
    numbers.add(i);
}

回答2:

If you want to have an object that looks like a List<Integer> that contains numbers from 0 up to N without actually storing those numbers, then you can implement your own list, for example like this:

import java.util.AbstractList;

public class RangeList extends AbstractList<Integer> {
    private final int size;

    public RangeList(int size) {
        this.size = size;
    }

    @Override
    public Integer get(int index) {
        return index;
    }

    @Override
    public int size() {
        return size;
    }
}

You can create an instance of it like this:

List<Integer> numbers = new RangeList(10);

It behaves just like a standard ArrayList<Integer> containing the values 0 to 9, but you cannot modify the list (adding, removing, modifying entries will lead to an UnsupportedOperationException).


回答3:

No matter how you decide to fill the ArrayList you will have to loop over or use each value that is stored into the ArrayList one by one. There is no faster way then iterating over each value and adding it to the ArrayList, only ways that make it look cleaner.

Creating a function that does so, or a an extension of the ArrayList object are two ways of doing so.

private ArrayList<Integer> fillRange(int min, int max){
    ArrayList<Integer> a_lst = new ArrayList<>();
    for(int i = min; i < max; i++){
        a_lst.add(i);
    }
    return a_lst;
}
  • 发表于 2019-02-28 21:16
  • 阅读 ( 206 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除