1/*
2 * Copyright (C) 2009 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.collect;
18
19import com.google.common.base.Preconditions;
20
21/**
22 * List returned by {@code ImmutableSortedSet.asList()} when the set isn't
23 * empty.
24 *
25 * @author Jared Levy
26 */
27@SuppressWarnings("serial")
28final class ImmutableSortedAsList<E> extends RegularImmutableList<E> {
29  private final transient ImmutableSortedSet<E> set;
30
31  ImmutableSortedAsList(Object[] array, int offset, int size,
32      ImmutableSortedSet<E> set) {
33    super(array, offset, size);
34    this.set = set;
35  }
36
37  // Override contains(), indexOf(), and lastIndexOf() to be O(log N) instead of
38  // O(N).
39
40  @Override public boolean contains(Object target) {
41    return set.indexOf(target) >= 0;
42  }
43
44  @Override public int indexOf(Object target) {
45    return set.indexOf(target);
46  }
47
48  @Override public int lastIndexOf(Object target) {
49    return set.indexOf(target);
50  }
51
52  // The returned ImmutableSortedAsList maintains the contains(), indexOf(), and
53  // lastIndexOf() performance benefits.
54  @Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
55    Preconditions.checkPositionIndexes(fromIndex, toIndex, size());
56    return (fromIndex == toIndex)
57        ? ImmutableList.<E>of()
58        : new RegularImmutableSortedSet<E>(
59            array(), set.comparator(),
60            offset() + fromIndex, offset() + toIndex).asList();
61  }
62
63  // The ImmutableAsList serialized form has the correct behavior.
64  @Override Object writeReplace() {
65    return new ImmutableAsList.SerializedForm(set);
66  }
67}
68