Skip to content

Commit

Permalink
Refactored IterableAsList to remove unnecessary call to size() and re…
Browse files Browse the repository at this point in the history
…move not working cache

no more calls to size() if not needed. Modifications in the underlying Iterable would lead to inconsistent cache. Removed cache completely.
Caches do not work for modifyable Iterables.
  • Loading branch information
Tim Hinkes committed Jun 10, 2017
1 parent ebee859 commit b99858d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 33 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ Note: [Checkstyle](https://en.wikipedia.org/wiki/Checkstyle) is used as a static
- [Andriy Kryvtsun](https://github.com/englishman)
- [Vseslav Sekorin](https://github.com/VsSekorin)
- [Andrey Valyaev](https://github.com/DronMDF)
- [Tim Hinkes](https://github.com/timmeey) [Blog](https://blog.timmeey.de)

## License (MIT)

Expand Down
49 changes: 16 additions & 33 deletions src/main/java/org/cactoos/list/IterableAsList.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
package org.cactoos.list;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import org.cactoos.func.StickyScalar;
import org.cactoos.func.UncheckedScalar;
Expand All @@ -48,11 +47,6 @@ public final class IterableAsList<T> extends AbstractList<T> {
*/
private final Iterable<T> source;

/**
* Cache for source.
*/
private final List<T> cache;

/**
* Iterable length.
*/
Expand All @@ -66,7 +60,6 @@ public final class IterableAsList<T> extends AbstractList<T> {
public IterableAsList(final Iterable<T> iterable) {
super();
this.source = iterable;
this.cache = new ArrayList<>(0);
this.length = new UncheckedScalar<>(
new StickyScalar<>(
new LengthOfIterable(iterable)
Expand All @@ -76,38 +69,28 @@ public IterableAsList(final Iterable<T> iterable) {

@Override
public T get(final int index) {
if (index < 0 || index >= this.size()) {
throw new IndexOutOfBoundsException(
new UncheckedText(
new FormattedText(
"index=%d, bounds=[%d; %d]",
index,
0,
this.size()
)
).asString()
);
int position = 0;
for (final T elem : this.source) {
if (position == index) {
return elem;
}
position += 1;
}
return this.cachedItem(index);
throw new IndexOutOfBoundsException(
new UncheckedText(
new FormattedText(
"index=%d, bounds=[%d; %d]",
index,
0,
this.size()
)
).asString()
);
}

@Override
public int size() {
return this.length.asValue();
}

/**
* Find item in cache by index.
*
* @param index Item index
* @return Cached item
*/
private T cachedItem(final int index) {
if (this.cache.size() != this.size()) {
for (final T item : this.source) {
this.cache.add(item);
}
}
return this.cache.get(index);
}
}

0 comments on commit b99858d

Please sign in to comment.