Shortest way to get an Iterator over a range of Integers in Java

后端 未结 7 1945
时光说笑
时光说笑 2020-12-29 22:27

What\'s the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:

/** 
* Returns an Iterator over the in         


        
相关标签:
7条回答
  • 2020-12-29 22:58

    It's generally considered good style to pass around Collection and friends instead of Iterator (see this FAQ entry), so I'd recommend something like

    public final class IntegerRange implements Set<Integer> {
            final LinkedHashSet<Integer> backingList;
            public IntegerRange(final int start, final int count) {
                    backingList = new LinkedHashSet(count, 1.0f);
                    for (int i=0; i < count; i++) {
                            backingList.set(i, start + i);
                    }       
            }       
            /** Insert a bunch of delegation methods here */
    }
    

    and then just use .iterator() when you need to pass an Iterator to whatever framework you're using.

    UPDATE: Obviously, this code isn't lazy. If you can't afford the extra memory overhead of storing (potentially) 2^32-1 Integers, you should use a different solution. Also, nothing about the type guarantees the range will be sorted (even though it is, based on the implementation). If you need to guarantee sorting, you could look into implementing SortedSet and backing it with a TreeSet, but it will take longer to build the range. Honestly, if you are that concerned with getting the details right, it might be worth your effort to look for a library. Tapestry has an internal version, for instance.

    0 讨论(0)
提交回复
热议问题