code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import junit.framework.TestCase;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Tests for {@link AtomicLongMap}.
*
* @author mike nonemacher
*/
@GwtCompatible(emulated = true)
public class AtomicLongMapTest extends TestCase {
private static final int ITERATIONS = 100;
private static final int MAX_ADDEND = 100;
private Random random = new Random(301);
public void testCreate_map() {
Map<String, Long> in = ImmutableMap.of("1", 1L, "2", 2L, "3", 3L);
AtomicLongMap<String> map = AtomicLongMap.create(in);
assertFalse(map.isEmpty());
assertSame(3, map.size());
assertTrue(map.containsKey("1"));
assertTrue(map.containsKey("2"));
assertTrue(map.containsKey("3"));
assertEquals(1L, map.get("1"));
assertEquals(2L, map.get("2"));
assertEquals(3L, map.get("3"));
}
public void testIncrementAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.incrementAndGet(key);
long after = map.get(key);
assertEquals(before + 1, after);
assertEquals(after, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(ITERATIONS, (int) map.get(key));
}
public void testIncrementAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(1L, map.incrementAndGet(key));
assertEquals(1L, map.get(key));
assertEquals(0L, map.decrementAndGet(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(1L, map.incrementAndGet(key));
assertEquals(1L, map.get(key));
}
public void testGetAndIncrement() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndIncrement(key);
long after = map.get(key);
assertEquals(before + 1, after);
assertEquals(before, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(ITERATIONS, (int) map.get(key));
}
public void testGetAndIncrement_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndIncrement(key));
assertEquals(1L, map.get(key));
assertEquals(1L, map.getAndDecrement(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndIncrement(key));
assertEquals(1L, map.get(key));
}
public void testDecrementAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.decrementAndGet(key);
long after = map.get(key);
assertEquals(before - 1, after);
assertEquals(after, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(-1 * ITERATIONS, (int) map.get(key));
}
public void testDecrementAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(-1L, map.decrementAndGet(key));
assertEquals(-1L, map.get(key));
assertEquals(0L, map.incrementAndGet(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(-1L, map.decrementAndGet(key));
assertEquals(-1L, map.get(key));
}
public void testGetAndDecrement() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndDecrement(key);
long after = map.get(key);
assertEquals(before - 1, after);
assertEquals(before, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(-1 * ITERATIONS, (int) map.get(key));
}
public void testGetAndDecrement_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndDecrement(key));
assertEquals(-1L, map.get(key));
assertEquals(-1L, map.getAndIncrement(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndDecrement(key));
assertEquals(-1L, map.get(key));
}
public void testAddAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long addend = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.addAndGet(key, addend);
long after = map.get(key);
assertEquals(before + addend, after);
assertEquals(after, result);
addend = after;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testAddAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(value, map.addAndGet(key, value));
assertEquals(value, map.get(key));
assertEquals(0L, map.addAndGet(key, -1 * value));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(value, map.addAndGet(key, value));
assertEquals(value, map.get(key));
}
public void testGetAndAdd() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long addend = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndAdd(key, addend);
long after = map.get(key);
assertEquals(before + addend, after);
assertEquals(before, result);
addend = after;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testGetAndAdd_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndAdd(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.getAndAdd(key, -1 * value));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndAdd(key, value));
assertEquals(value, map.get(key));
}
public void testPut() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.put(key, newValue);
long after = map.get(key);
assertEquals(newValue, after);
assertEquals(before, result);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testPut_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.put(key, value));
assertEquals(value, map.get(key));
}
public void testPutAll() {
Map<String, Long> in = ImmutableMap.of("1", 1L, "2", 2L, "3", 3L);
AtomicLongMap<String> map = AtomicLongMap.create();
assertTrue(map.isEmpty());
assertSame(0, map.size());
assertFalse(map.containsKey("1"));
assertFalse(map.containsKey("2"));
assertFalse(map.containsKey("3"));
assertEquals(0L, map.get("1"));
assertEquals(0L, map.get("2"));
assertEquals(0L, map.get("3"));
map.putAll(in);
assertFalse(map.isEmpty());
assertSame(3, map.size());
assertTrue(map.containsKey("1"));
assertTrue(map.containsKey("2"));
assertTrue(map.containsKey("3"));
assertEquals(1L, map.get("1"));
assertEquals(2L, map.get("2"));
assertEquals(3L, map.get("3"));
}
public void testPutIfAbsent() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.putIfAbsent(key, newValue);
long after = map.get(key);
assertEquals(before, result);
assertEquals(before == 0 ? newValue : before, after);
map.remove(key);
before = map.get(key);
result = map.putIfAbsent(key, newValue);
after = map.get(key);
assertEquals(0, before);
assertEquals(before, result);
assertEquals(newValue, after);
map.put(key, 0L);
before = map.get(key);
result = map.putIfAbsent(key, newValue);
after = map.get(key);
assertEquals(0, before);
assertEquals(before, result);
assertEquals(newValue, after);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testPutIfAbsent_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.putIfAbsent(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.putIfAbsent(key, value));
assertEquals(value, map.get(key));
}
public void testReplace() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
assertFalse(map.replace(key, before + 1, newValue + 1));
assertFalse(map.replace(key, before - 1, newValue - 1));
assertTrue(map.replace(key, before, newValue));
long after = map.get(key);
assertEquals(newValue, after);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testReplace_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertTrue(map.replace(key, 0L, value));
assertEquals(value, map.get(key));
assertTrue(map.replace(key, value, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertTrue(map.replace(key, 0L, value));
assertEquals(value, map.get(key));
}
public void testRemove() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertEquals(0L, map.remove(key));
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
map.put(key, newValue);
assertTrue(map.containsKey(key));
long before = map.get(key);
long result = map.remove(key);
long after = map.get(key);
assertFalse(map.containsKey(key));
assertEquals(before, result);
assertEquals(0L, after);
newValue += newValue;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testRemove_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.remove(key));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.remove(key));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
}
public void testRemoveValue() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertFalse(map.remove(key, 0L));
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
map.put(key, newValue);
assertTrue(map.containsKey(key));
long before = map.get(key);
assertFalse(map.remove(key, newValue + 1));
assertFalse(map.remove(key, newValue - 1));
assertTrue(map.remove(key, newValue));
long after = map.get(key);
assertFalse(map.containsKey(key));
assertEquals(0L, after);
newValue += newValue;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testRemoveValue_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertFalse(map.remove(key, 0L));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertTrue(map.remove(key, 0L));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
}
public void testRemoveZeros() {
AtomicLongMap<Object> map = AtomicLongMap.create();
Set<Object> nonZeroKeys = Sets.newHashSet();
for (int i = 0; i < ITERATIONS; i++) {
Object key = new Object();
long value = i % 2;
map.put(key, value);
if (value != 0L) {
nonZeroKeys.add(key);
}
}
assertEquals(ITERATIONS, map.size());
assertTrue(map.asMap().containsValue(0L));
map.removeAllZeros();
assertFalse(map.asMap().containsValue(0L));
assertEquals(ITERATIONS / 2, map.size());
assertEquals(nonZeroKeys, map.asMap().keySet());
}
public void testClear() {
AtomicLongMap<Object> map = AtomicLongMap.create();
for (int i = 0; i < ITERATIONS; i++) {
map.put(new Object(), i);
}
assertEquals(ITERATIONS, map.size());
map.clear();
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testSum() {
AtomicLongMap<Object> map = AtomicLongMap.create();
long sum = 0;
for (int i = 0; i < ITERATIONS; i++) {
map.put(new Object(), i);
sum += i;
}
assertEquals(ITERATIONS, map.size());
assertEquals(sum, map.sum());
}
public void testEmpty() {
AtomicLongMap<String> map = AtomicLongMap.create();
assertEquals(0L, map.get("a"));
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertFalse(map.remove("a", 1L));
assertFalse(map.remove("a", 0L));
assertFalse(map.replace("a", 1L, 0L));
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.io.BaseEncoding.base32;
import static com.google.common.io.BaseEncoding.base32Hex;
import static com.google.common.io.BaseEncoding.base64;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.io.BaseEncoding.DecodingException;
import junit.framework.TestCase;
import java.io.UnsupportedEncodingException;
/**
* Tests for {@code BaseEncoding}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BaseEncodingTest extends TestCase {
public static void assertEquals(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i]);
}
}
public void testSeparatorsExplicitly() {
testEncodes(base64().withSeparator("\n", 3), "foobar", "Zm9\nvYm\nFy");
testEncodes(base64().withSeparator("$", 4), "foobar", "Zm9v$YmFy");
testEncodes(base32().withSeparator("*", 4), "foobar", "MZXW*6YTB*OI==*====");
}
@SuppressWarnings("ReturnValueIgnored")
public void testSeparatorSameAsPadChar() {
try {
base64().withSeparator("=", 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
base64().withPadChar('#').withSeparator("!#!", 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
@SuppressWarnings("ReturnValueIgnored")
public void testAtMostOneSeparator() {
BaseEncoding separated = base64().withSeparator("\n", 3);
try {
separated.withSeparator("$", 4);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
public void testBase64() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithSeparators(base64(), "", "");
testEncodingWithSeparators(base64(), "f", "Zg==");
testEncodingWithSeparators(base64(), "fo", "Zm8=");
testEncodingWithSeparators(base64(), "foo", "Zm9v");
testEncodingWithSeparators(base64(), "foob", "Zm9vYg==");
testEncodingWithSeparators(base64(), "fooba", "Zm9vYmE=");
testEncodingWithSeparators(base64(), "foobar", "Zm9vYmFy");
}
public void testBase64LenientPadding() {
testDecodes(base64(), "Zg", "f");
testDecodes(base64(), "Zg=", "f");
testDecodes(base64(), "Zg==", "f"); // proper padding length
testDecodes(base64(), "Zg===", "f");
testDecodes(base64(), "Zg====", "f");
}
public void testBase64InvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base64(), "\u007f");
assertFailsToDecode(base64(), "Wf2!");
// This sentence just isn't base64() encoded.
assertFailsToDecode(base64(), "let's not talk of love or chains!");
// A 4n+1 length string is never legal base64().
assertFailsToDecode(base64(), "12345");
}
@SuppressWarnings("ReturnValueIgnored")
public void testBase64CannotUpperCase() {
try {
base64().upperCase();
fail();
} catch (IllegalStateException expected) {
// success
}
}
@SuppressWarnings("ReturnValueIgnored")
public void testBase64CannotLowerCase() {
try {
base64().lowerCase();
fail();
} catch (IllegalStateException expected) {
// success
}
}
public void testBase64AlternatePadding() {
BaseEncoding enc = base64().withPadChar('~');
testEncodingWithSeparators(enc, "", "");
testEncodingWithSeparators(enc, "f", "Zg~~");
testEncodingWithSeparators(enc, "fo", "Zm8~");
testEncodingWithSeparators(enc, "foo", "Zm9v");
testEncodingWithSeparators(enc, "foob", "Zm9vYg~~");
testEncodingWithSeparators(enc, "fooba", "Zm9vYmE~");
testEncodingWithSeparators(enc, "foobar", "Zm9vYmFy");
}
public void testBase64OmitPadding() {
BaseEncoding enc = base64().omitPadding();
testEncodingWithSeparators(enc, "", "");
testEncodingWithSeparators(enc, "f", "Zg");
testEncodingWithSeparators(enc, "fo", "Zm8");
testEncodingWithSeparators(enc, "foo", "Zm9v");
testEncodingWithSeparators(enc, "foob", "Zm9vYg");
testEncodingWithSeparators(enc, "fooba", "Zm9vYmE");
testEncodingWithSeparators(enc, "foobar", "Zm9vYmFy");
}
public void testBase32() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithCasing(base32(), "", "");
testEncodingWithCasing(base32(), "f", "MY======");
testEncodingWithCasing(base32(), "fo", "MZXQ====");
testEncodingWithCasing(base32(), "foo", "MZXW6===");
testEncodingWithCasing(base32(), "foob", "MZXW6YQ=");
testEncodingWithCasing(base32(), "fooba", "MZXW6YTB");
testEncodingWithCasing(base32(), "foobar", "MZXW6YTBOI======");
}
public void testBase32LenientPadding() {
testDecodes(base32(), "MZXW6", "foo");
testDecodes(base32(), "MZXW6=", "foo");
testDecodes(base32(), "MZXW6==", "foo");
testDecodes(base32(), "MZXW6===", "foo"); // proper padding length
testDecodes(base32(), "MZXW6====", "foo");
testDecodes(base32(), "MZXW6=====", "foo");
}
public void testBase32AlternatePadding() {
BaseEncoding enc = base32().withPadChar('~');
testEncodingWithCasing(enc, "", "");
testEncodingWithCasing(enc, "f", "MY~~~~~~");
testEncodingWithCasing(enc, "fo", "MZXQ~~~~");
testEncodingWithCasing(enc, "foo", "MZXW6~~~");
testEncodingWithCasing(enc, "foob", "MZXW6YQ~");
testEncodingWithCasing(enc, "fooba", "MZXW6YTB");
testEncodingWithCasing(enc, "foobar", "MZXW6YTBOI~~~~~~");
}
public void testBase32InvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base32(), "\u007f");
assertFailsToDecode(base32(), "Wf2!");
// This sentence just isn't base32() encoded.
assertFailsToDecode(base32(), "let's not talk of love or chains!");
// An 8n+{1,3,6} length string is never legal base32.
assertFailsToDecode(base32(), "A");
assertFailsToDecode(base32(), "ABC");
assertFailsToDecode(base32(), "ABCDEF");
}
public void testBase32UpperCaseIsNoOp() {
assertSame(base32(), base32().upperCase());
}
public void testBase32Hex() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithCasing(base32Hex(), "", "");
testEncodingWithCasing(base32Hex(), "f", "CO======");
testEncodingWithCasing(base32Hex(), "fo", "CPNG====");
testEncodingWithCasing(base32Hex(), "foo", "CPNMU===");
testEncodingWithCasing(base32Hex(), "foob", "CPNMUOG=");
testEncodingWithCasing(base32Hex(), "fooba", "CPNMUOJ1");
testEncodingWithCasing(base32Hex(), "foobar", "CPNMUOJ1E8======");
}
public void testBase32HexLenientPadding() {
testDecodes(base32Hex(), "CPNMU", "foo");
testDecodes(base32Hex(), "CPNMU=", "foo");
testDecodes(base32Hex(), "CPNMU==", "foo");
testDecodes(base32Hex(), "CPNMU===", "foo"); // proper padding length
testDecodes(base32Hex(), "CPNMU====", "foo");
testDecodes(base32Hex(), "CPNMU=====", "foo");
}
public void testBase32HexInvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base32Hex(), "\u007f");
assertFailsToDecode(base32Hex(), "Wf2!");
// This sentence just isn't base32 encoded.
assertFailsToDecode(base32Hex(), "let's not talk of love or chains!");
// An 8n+{1,3,6} length string is never legal base32.
assertFailsToDecode(base32Hex(), "A");
assertFailsToDecode(base32Hex(), "ABC");
assertFailsToDecode(base32Hex(), "ABCDEF");
}
public void testBase32HexUpperCaseIsNoOp() {
assertSame(base32Hex(), base32Hex().upperCase());
}
public void testBase16() {
testEncodingWithCasing(base16(), "", "");
testEncodingWithCasing(base16(), "f", "66");
testEncodingWithCasing(base16(), "fo", "666F");
testEncodingWithCasing(base16(), "foo", "666F6F");
testEncodingWithCasing(base16(), "foob", "666F6F62");
testEncodingWithCasing(base16(), "fooba", "666F6F6261");
testEncodingWithCasing(base16(), "foobar", "666F6F626172");
}
public void testBase16UpperCaseIsNoOp() {
assertSame(base16(), base16().upperCase());
}
private static void testEncodingWithCasing(
BaseEncoding encoding, String decoded, String encoded) {
testEncodingWithSeparators(encoding, decoded, encoded);
testEncodingWithSeparators(encoding.upperCase(), decoded, Ascii.toUpperCase(encoded));
testEncodingWithSeparators(encoding.lowerCase(), decoded, Ascii.toLowerCase(encoded));
}
private static void testEncodingWithSeparators(
BaseEncoding encoding, String decoded, String encoded) {
testEncoding(encoding, decoded, encoded);
// test separators work
for (int sepLength = 3; sepLength <= 5; sepLength++) {
for (String separator : ImmutableList.of(",", "\n", ";;", "")) {
testEncoding(encoding.withSeparator(separator, sepLength), decoded,
Joiner.on(separator).join(Splitter.fixedLength(sepLength).split(encoded)));
}
}
}
private static void testEncoding(BaseEncoding encoding, String decoded, String encoded) {
testEncodes(encoding, decoded, encoded);
testDecodes(encoding, encoded, decoded);
}
private static void testEncodes(BaseEncoding encoding, String decoded, String encoded) {
byte[] bytes;
try {
// GWT does not support String.getBytes(Charset)
bytes = decoded.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
assertEquals(encoded, encoding.encode(bytes));
}
private static void testDecodes(BaseEncoding encoding, String encoded, String decoded) {
byte[] bytes;
try {
// GWT does not support String.getBytes(Charset)
bytes = decoded.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
assertEquals(bytes, encoding.decode(encoded));
}
private static void assertFailsToDecode(BaseEncoding encoding, String cannotDecode) {
try {
encoding.decode(cannotDecode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// success
}
try {
encoding.decodeChecked(cannotDecode);
fail("Expected DecodingException");
} catch (DecodingException expected) {
// success
}
}
public void testToString() {
assertEquals("BaseEncoding.base64().withPadChar(=)", BaseEncoding.base64().toString());
assertEquals("BaseEncoding.base32Hex().omitPadding()",
BaseEncoding.base32Hex().omitPadding().toString());
assertEquals("BaseEncoding.base32().lowerCase().withPadChar($)",
BaseEncoding.base32().lowerCase().withPadChar('$').toString());
assertEquals("BaseEncoding.base16().withSeparator(\"\n\", 10)",
BaseEncoding.base16().withSeparator("\n", 10).toString());
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code Predicate} instances.
*
* <p>All methods returns serializable predicates as long as they're given
* serializable parameters.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the
* use of {@code Predicate}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Predicates {
private Predicates() {}
// TODO(kevinb): considering having these implement a VisitablePredicate
// interface which specifies an accept(PredicateVisitor) method.
/**
* Returns a predicate that always evaluates to {@code true}.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysTrue() {
return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
}
/**
* Returns a predicate that always evaluates to {@code false}.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysFalse() {
return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is null.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> isNull() {
return ObjectPredicate.IS_NULL.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is not null.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> notNull() {
return ObjectPredicate.NOT_NULL.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the given predicate
* evaluates to {@code false}.
*/
public static <T> Predicate<T> not(Predicate<T> predicate) {
return new NotPredicate<T>(predicate);
}
/**
* Returns a predicate that evaluates to {@code true} if each of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found. It defensively copies the iterable passed in, so future
* changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* true}.
*/
public static <T> Predicate<T> and(
Iterable<? extends Predicate<? super T>> components) {
return new AndPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if each of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found. It defensively copies the array passed in, so future
* changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* true}.
*/
public static <T> Predicate<T> and(Predicate<? super T>... components) {
return new AndPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if both of its
* components evaluate to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found.
*/
public static <T> Predicate<T> and(Predicate<? super T> first,
Predicate<? super T> second) {
return new AndPredicate<T>(Predicates.<T>asList(
checkNotNull(first), checkNotNull(second)));
}
/**
* Returns a predicate that evaluates to {@code true} if any one of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found. It defensively copies the iterable passed in, so
* future changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* false}.
*/
public static <T> Predicate<T> or(
Iterable<? extends Predicate<? super T>> components) {
return new OrPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if any one of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found. It defensively copies the array passed in, so
* future changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* false}.
*/
public static <T> Predicate<T> or(Predicate<? super T>... components) {
return new OrPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if either of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found.
*/
public static <T> Predicate<T> or(
Predicate<? super T> first, Predicate<? super T> second) {
return new OrPredicate<T>(Predicates.<T>asList(
checkNotNull(first), checkNotNull(second)));
}
/**
* Returns a predicate that evaluates to {@code true} if the object being
* tested {@code equals()} the given target or both are null.
*/
public static <T> Predicate<T> equalTo(@Nullable T target) {
return (target == null)
? Predicates.<T>isNull()
: new IsEqualToPredicate<T>(target);
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is a member of the given collection. It does not defensively
* copy the collection passed in, so future changes to it will alter the
* behavior of the predicate.
*
* <p>This method can technically accept any {@code Collection<?>}, but using
* a typed collection helps prevent bugs. This approach doesn't block any
* potential users since it is always possible to use {@code
* Predicates.<Object>in()}.
*
* @param target the collection that may contain the function input
*/
public static <T> Predicate<T> in(Collection<? extends T> target) {
return new InPredicate<T>(target);
}
/**
* Returns the composition of a function and a predicate. For every {@code x},
* the generated predicate returns {@code predicate(function(x))}.
*
* @return the composition of the provided function and predicate
*/
public static <A, B> Predicate<A> compose(
Predicate<B> predicate, Function<A, ? extends B> function) {
return new CompositionPredicate<A, B>(predicate, function);
}
// End public API, begin private implementation classes.
// Package private for GWT serialization.
enum ObjectPredicate implements Predicate<Object> {
ALWAYS_TRUE {
@Override public boolean apply(@Nullable Object o) {
return true;
}
},
ALWAYS_FALSE {
@Override public boolean apply(@Nullable Object o) {
return false;
}
},
IS_NULL {
@Override public boolean apply(@Nullable Object o) {
return o == null;
}
},
NOT_NULL {
@Override public boolean apply(@Nullable Object o) {
return o != null;
}
};
@SuppressWarnings("unchecked") // these Object predicates work for any T
<T> Predicate<T> withNarrowedType() {
return (Predicate<T>) this;
}
}
/** @see Predicates#not(Predicate) */
private static class NotPredicate<T> implements Predicate<T>, Serializable {
final Predicate<T> predicate;
NotPredicate(Predicate<T> predicate) {
this.predicate = checkNotNull(predicate);
}
@Override
public boolean apply(@Nullable T t) {
return !predicate.apply(t);
}
@Override public int hashCode() {
return ~predicate.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof NotPredicate) {
NotPredicate<?> that = (NotPredicate<?>) obj;
return predicate.equals(that.predicate);
}
return false;
}
@Override public String toString() {
return "Not(" + predicate.toString() + ")";
}
private static final long serialVersionUID = 0;
}
private static final Joiner COMMA_JOINER = Joiner.on(",");
/** @see Predicates#and(Iterable) */
private static class AndPredicate<T> implements Predicate<T>, Serializable {
private final List<? extends Predicate<? super T>> components;
private AndPredicate(List<? extends Predicate<? super T>> components) {
this.components = components;
}
@Override
public boolean apply(@Nullable T t) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (!components.get(i).apply(t)) {
return false;
}
}
return true;
}
@Override public int hashCode() {
// add a random number to avoid collisions with OrPredicate
return components.hashCode() + 0x12472c2c;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof AndPredicate) {
AndPredicate<?> that = (AndPredicate<?>) obj;
return components.equals(that.components);
}
return false;
}
@Override public String toString() {
return "And(" + COMMA_JOINER.join(components) + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#or(Iterable) */
private static class OrPredicate<T> implements Predicate<T>, Serializable {
private final List<? extends Predicate<? super T>> components;
private OrPredicate(List<? extends Predicate<? super T>> components) {
this.components = components;
}
@Override
public boolean apply(@Nullable T t) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (components.get(i).apply(t)) {
return true;
}
}
return false;
}
@Override public int hashCode() {
// add a random number to avoid collisions with AndPredicate
return components.hashCode() + 0x053c91cf;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof OrPredicate) {
OrPredicate<?> that = (OrPredicate<?>) obj;
return components.equals(that.components);
}
return false;
}
@Override public String toString() {
return "Or(" + COMMA_JOINER.join(components) + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#equalTo(Object) */
private static class IsEqualToPredicate<T>
implements Predicate<T>, Serializable {
private final T target;
private IsEqualToPredicate(T target) {
this.target = target;
}
@Override
public boolean apply(T t) {
return target.equals(t);
}
@Override public int hashCode() {
return target.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof IsEqualToPredicate) {
IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
return target.equals(that.target);
}
return false;
}
@Override public String toString() {
return "IsEqualTo(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#in(Collection) */
private static class InPredicate<T> implements Predicate<T>, Serializable {
private final Collection<?> target;
private InPredicate(Collection<?> target) {
this.target = checkNotNull(target);
}
@Override
public boolean apply(@Nullable T t) {
try {
return target.contains(t);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof InPredicate) {
InPredicate<?> that = (InPredicate<?>) obj;
return target.equals(that.target);
}
return false;
}
@Override public int hashCode() {
return target.hashCode();
}
@Override public String toString() {
return "In(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#compose(Predicate, Function) */
private static class CompositionPredicate<A, B>
implements Predicate<A>, Serializable {
final Predicate<B> p;
final Function<A, ? extends B> f;
private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
this.p = checkNotNull(p);
this.f = checkNotNull(f);
}
@Override
public boolean apply(@Nullable A a) {
return p.apply(f.apply(a));
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof CompositionPredicate) {
CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
return f.equals(that.f) && p.equals(that.p);
}
return false;
}
@Override public int hashCode() {
return f.hashCode() ^ p.hashCode();
}
@Override public String toString() {
return p.toString() + "(" + f.toString() + ")";
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <T> List<Predicate<? super T>> asList(
Predicate<? super T> first, Predicate<? super T> second) {
return Arrays.<Predicate<? super T>>asList(first, second);
}
private static <T> List<T> defensiveCopy(T... array) {
return defensiveCopy(Arrays.asList(array));
}
static <T> List<T> defensiveCopy(Iterable<T> iterable) {
ArrayList<T> list = new ArrayList<T>();
for (T element : iterable) {
list.add(checkNotNull(element));
}
return list;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.concurrent.TimeUnit;
/**
* An object that measures elapsed time in nanoseconds. It is useful to measure
* elapsed time using this class instead of direct calls to {@link
* System#nanoTime} for a few reasons:
*
* <ul>
* <li>An alternate time source can be substituted, for testing or performance
* reasons.
* <li>As documented by {@code nanoTime}, the value returned has no absolute
* meaning, and can only be interpreted as relative to another timestamp
* returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
* more effective abstraction because it exposes only these relative values,
* not the absolute ones.
* </ul>
*
* <p>Basic usage:
* <pre>
* Stopwatch stopwatch = Stopwatch.{@link #createStarted createStarted}();
* doSomething();
* stopwatch.{@link #stop stop}(); // optional
*
* long millis = stopwatch.elapsed(MILLISECONDS);
*
* log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
* </pre>
*
* <p>Stopwatch methods are not idempotent; it is an error to start or stop a
* stopwatch that is already in the desired state.
*
* <p>When testing code that uses this class, use the {@linkplain
* #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.
* <!-- TODO(kevinb): restore the "such as" --> This allows you to
* simulate any valid behavior of the stopwatch.
*
* <p><b>Note:</b> This class is not thread-safe.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class Stopwatch {
private final Ticker ticker;
private boolean isRunning;
private long elapsedNanos;
private long startTick;
/**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime}
* as its time source.
*
* @since 15.0
*/
public static Stopwatch createUnstarted() {
return new Stopwatch();
}
/**
* Creates (but does not start) a new stopwatch, using the specified time
* source.
*
* @since 15.0
*/
public static Stopwatch createUnstarted(Ticker ticker) {
return new Stopwatch(ticker);
}
/**
* Creates (and starts) a new stopwatch using {@link System#nanoTime}
* as its time source.
*
* @since 15.0
*/
public static Stopwatch createStarted() {
return new Stopwatch().start();
}
/**
* Creates (and starts) a new stopwatch, using the specified time
* source.
*
* @since 15.0
*/
public static Stopwatch createStarted(Ticker ticker) {
return new Stopwatch(ticker).start();
}
/**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime}
* as its time source.
*
* @deprecated Use {@link Stopwatch#createUnstarted()} instead. This
* constructor is scheduled to be remove in Guava release 17.0.
*/
@Deprecated
public Stopwatch() {
this(Ticker.systemTicker());
}
/**
* Creates (but does not start) a new stopwatch, using the specified time
* source.
*
* @deprecated Use {@link Stopwatch#createUnstarted(Ticker)} instead. This
* constructor is scheduled to be remove in Guava release 17.0.
*/
@Deprecated
public Stopwatch(Ticker ticker) {
this.ticker = checkNotNull(ticker, "ticker");
}
/**
* Returns {@code true} if {@link #start()} has been called on this stopwatch,
* and {@link #stop()} has not been called since the last call to {@code
* start()}.
*/
public boolean isRunning() {
return isRunning;
}
/**
* Starts the stopwatch.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already running.
*/
public Stopwatch start() {
checkState(!isRunning, "This stopwatch is already running.");
isRunning = true;
startTick = ticker.read();
return this;
}
/**
* Stops the stopwatch. Future reads will return the fixed duration that had
* elapsed up to this point.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already stopped.
*/
public Stopwatch stop() {
long tick = ticker.read();
checkState(isRunning, "This stopwatch is already stopped.");
isRunning = false;
elapsedNanos += tick - startTick;
return this;
}
/**
* Sets the elapsed time for this stopwatch to zero,
* and places it in a stopped state.
*
* @return this {@code Stopwatch} instance
*/
public Stopwatch reset() {
elapsedNanos = 0;
isRunning = false;
return this;
}
private long elapsedNanos() {
return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed
* in the desired time unit, with any fraction rounded down.
*
* <p>Note that the overhead of measurement can be more than a microsecond, so
* it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
* precision here.
*
* @since 14.0 (since 10.0 as {@code elapsedTime()})
*/
public long elapsed(TimeUnit desiredUnit) {
return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed
* in the desired time unit, with any fraction rounded down.
*
* <p>Note that the overhead of measurement can be more than a microsecond, so
* it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
* precision here.
*
* @deprecated Use {@link Stopwatch#elapsed(TimeUnit)} instead. This method is
* scheduled to be removed in Guava release 16.0.
*/
@Deprecated
public long elapsedTime(TimeUnit desiredUnit) {
return elapsed(desiredUnit);
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed
* in milliseconds, with any fraction rounded down. This is identical to
* {@code elapsed(TimeUnit.MILLISECONDS)}.
*
* @deprecated Use {@code stopwatch.elapsed(MILLISECONDS)} instead. This
* method is scheduled to be removed in Guava release 16.0.
*/
@Deprecated
public long elapsedMillis() {
return elapsed(MILLISECONDS);
}
private static TimeUnit chooseUnit(long nanos) {
if (DAYS.convert(nanos, NANOSECONDS) > 0) {
return DAYS;
}
if (HOURS.convert(nanos, NANOSECONDS) > 0) {
return HOURS;
}
if (MINUTES.convert(nanos, NANOSECONDS) > 0) {
return MINUTES;
}
if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
}
private static String abbreviate(TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs"; // μs
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
case MINUTES:
return "min";
case HOURS:
return "h";
case DAYS:
return "d";
default:
throw new AssertionError();
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import java.util.concurrent.TimeUnit;
/**
* @author Jesse Wilson
*/
class Platform {
private static final char[] CHAR_BUFFER = new char[1024];
static char[] charBufferFromThreadLocal() {
// ThreadLocal is not available to GWT, so we always reuse the same
// instance. It is always safe to return the same instance because
// javascript is single-threaded, and only used by blocks that doesn't
// involve async callbacks.
return CHAR_BUFFER;
}
static CharMatcher precomputeCharMatcher(CharMatcher matcher) {
// CharMatcher.precomputed() produces CharMatchers that are maybe a little
// faster (and that's debatable), but definitely more memory-hungry. We're
// choosing to turn .precomputed() into a no-op in GWT, because it doesn't
// seem to be a worthwhile tradeoff in a browser.
return matcher;
}
static long systemNanoTime() {
// System.nanoTime() is not available in GWT, so we get milliseconds
// and convert to nanos.
return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* Utility methods for working with {@link Enum} instances.
*
* @author Steve McKay
*
* @since 9.0
*/
@GwtCompatible(emulated = true)
@Beta
public final class Enums {
private Enums() {}
/**
* Returns a {@link Function} that maps an {@link Enum} name to the associated
* {@code Enum} constant. The {@code Function} will return {@code null} if the
* {@code Enum} constant does not exist.
*
* @param enumClass the {@link Class} of the {@code Enum} declaring the
* constant values.
*/
public static <T extends Enum<T>> Function<String, T> valueOfFunction(Class<T> enumClass) {
return new ValueOfFunction<T>(enumClass);
}
/**
* A {@link Function} that maps an {@link Enum} name to the associated
* constant, or {@code null} if the constant does not exist.
*/
private static final class ValueOfFunction<T extends Enum<T>>
implements Function<String, T>, Serializable {
private final Class<T> enumClass;
private ValueOfFunction(Class<T> enumClass) {
this.enumClass = checkNotNull(enumClass);
}
@Override
public T apply(String value) {
try {
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
return null;
}
}
@Override public boolean equals(@Nullable Object obj) {
return obj instanceof ValueOfFunction &&
enumClass.equals(((ValueOfFunction) obj).enumClass);
}
@Override public int hashCode() {
return enumClass.hashCode();
}
@Override public String toString() {
return "Enums.valueOf(" + enumClass + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
* constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
* user input or falling back to a default enum constant. For example,
* {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
*
* @since 12.0
*/
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
checkNotNull(enumClass);
checkNotNull(value);
try {
return Optional.of(Enum.valueOf(enumClass, value));
} catch (IllegalArgumentException iae) {
return Optional.absent();
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckReturnValue;
/**
* Extracts non-overlapping substrings from an input string, typically by
* recognizing appearances of a <i>separator</i> sequence. This separator can be
* specified as a single {@linkplain #on(char) character}, fixed {@linkplain
* #on(String) string}, {@linkplain #onPattern regular expression} or {@link
* #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at
* all, a splitter can extract adjacent substrings of a given {@linkplain
* #fixedLength fixed length}.
*
* <p>For example, this expression: <pre> {@code
*
* Splitter.on(',').split("foo,bar,qux")}</pre>
*
* ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and
* {@code "qux"}, in that order.
*
* <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The
* following expression: <pre> {@code
*
* Splitter.on(',').split(" foo,,, bar ,")}</pre>
*
* ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this
* is not the desired behavior, use configuration methods to obtain a <i>new</i>
* splitter instance with modified behavior: <pre> {@code
*
* private static final Splitter MY_SPLITTER = Splitter.on(',')
* .trimResults()
* .omitEmptyStrings();}</pre>
*
* <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo",
* "bar"]}. Note that the order in which these configuration methods are called
* is never significant.
*
* <p><b>Warning:</b> Splitter instances are immutable. Invoking a configuration
* method has no effect on the receiving instance; you must store and use the
* new splitter instance it returns instead. <pre> {@code
*
* // Do NOT do this
* Splitter splitter = Splitter.on('/');
* splitter.trimResults(); // does nothing!
* return splitter.split("wrong / wrong / wrong");}</pre>
*
* <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an
* input string containing {@code n} occurrences of the separator naturally
* yields an iterable of size {@code n + 1}. So if the separator does not occur
* anywhere in the input, a single substring is returned containing the entire
* input. Consequently, all splitters split the empty string to {@code [""]}
* (note: even fixed-length splitters).
*
* <p>Splitter instances are thread-safe immutable, and are therefore safe to
* store as {@code static final} constants.
*
* <p>The {@link Joiner} class provides the inverse operation to splitting, but
* note that a round-trip between the two should be assumed to be lossy.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter">
* {@code Splitter}</a>.
*
* @author Julien Silland
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Splitter {
private final CharMatcher trimmer;
private final boolean omitEmptyStrings;
private final Strategy strategy;
private final int limit;
private Splitter(Strategy strategy) {
this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE);
}
private Splitter(Strategy strategy, boolean omitEmptyStrings,
CharMatcher trimmer, int limit) {
this.strategy = strategy;
this.omitEmptyStrings = omitEmptyStrings;
this.trimmer = trimmer;
this.limit = limit;
}
/**
* Returns a splitter that uses the given single-character separator. For
* example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable
* containing {@code ["foo", "", "bar"]}.
*
* @param separator the character to recognize as a separator
* @return a splitter, with default settings, that recognizes that separator
*/
public static Splitter on(char separator) {
return on(CharMatcher.is(separator));
}
/**
* Returns a splitter that considers any single character matched by the
* given {@code CharMatcher} to be a separator. For example, {@code
* Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an
* iterable containing {@code ["foo", "", "bar", "quux"]}.
*
* @param separatorMatcher a {@link CharMatcher} that determines whether a
* character is a separator
* @return a splitter, with default settings, that uses this matcher
*/
public static Splitter on(final CharMatcher separatorMatcher) {
checkNotNull(separatorMatcher);
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
Splitter splitter, final CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override int separatorStart(int start) {
return separatorMatcher.indexIn(toSplit, start);
}
@Override int separatorEnd(int separatorPosition) {
return separatorPosition + 1;
}
};
}
});
}
/**
* Returns a splitter that uses the given fixed string as a separator. For
* example, {@code Splitter.on(", ").split("foo, bar,baz")} returns an
* iterable containing {@code ["foo", "bar,baz"]}.
*
* @param separator the literal, nonempty string to recognize as a separator
* @return a splitter, with default settings, that recognizes that separator
*/
public static Splitter on(final String separator) {
checkArgument(separator.length() != 0,
"The separator may not be the empty string.");
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
int delimeterLength = separator.length();
positions:
for (int p = start, last = toSplit.length() - delimeterLength;
p <= last; p++) {
for (int i = 0; i < delimeterLength; i++) {
if (toSplit.charAt(i + p) != separator.charAt(i)) {
continue positions;
}
}
return p;
}
return -1;
}
@Override public int separatorEnd(int separatorPosition) {
return separatorPosition + separator.length();
}
};
}
});
}
/**
* Returns a splitter that divides strings into pieces of the given length.
* For example, {@code Splitter.fixedLength(2).split("abcde")} returns an
* iterable containing {@code ["ab", "cd", "e"]}. The last piece can be
* smaller than {@code length} but will never be empty.
*
* <p><b>Exception:</b> for consistency with separator-based splitters, {@code
* split("")} does not yield an empty iterable, but an iterable containing
* {@code ""}. This is the only case in which {@code
* Iterables.size(split(input))} does not equal {@code
* IntMath.divide(input.length(), length, CEILING)}. To avoid this behavior,
* use {@code omitEmptyStrings}.
*
* @param length the desired length of pieces after splitting, a positive
* integer
* @return a splitter, with default settings, that can split into fixed sized
* pieces
* @throws IllegalArgumentException if {@code length} is zero or negative
*/
public static Splitter fixedLength(final int length) {
checkArgument(length > 0, "The length may not be less than 1");
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
final Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
int nextChunkStart = start + length;
return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
}
@Override public int separatorEnd(int separatorPosition) {
return separatorPosition;
}
};
}
});
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* automatically omits empty strings from the results. For example, {@code
* Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an
* iterable containing only {@code ["a", "b", "c"]}.
*
* <p>If either {@code trimResults} option is also specified when creating a
* splitter, that splitter always trims results first before checking for
* emptiness. So, for example, {@code
* Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns
* an empty iterable.
*
* <p>Note that it is ordinarily not possible for {@link #split(CharSequence)}
* to return an empty iterable, but when using this option, it can (if the
* input sequence consists of nothing but separators).
*
* @return a splitter with the desired configuration
*/
@CheckReturnValue
public Splitter omitEmptyStrings() {
return new Splitter(strategy, true, trimmer, limit);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter but
* stops splitting after it reaches the limit.
* The limit defines the maximum number of items returned by the iterator.
*
* <p>For example,
* {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable
* containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the
* omitted strings do no count. Hence,
* {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")}
* returns an iterable containing {@code ["a", "b", "c,d"}.
* When trim is requested, all entries, including the last are trimmed. Hence
* {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")}
* results in @{code ["a", "b", "c , d"]}.
*
* @param limit the maximum number of items returns
* @return a splitter with the desired configuration
* @since 9.0
*/
@CheckReturnValue
public Splitter limit(int limit) {
checkArgument(limit > 0, "must be greater than zero: %s", limit);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* automatically removes leading and trailing {@linkplain
* CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent
* to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code
* Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable
* containing {@code ["a", "b", "c"]}.
*
* @return a splitter with the desired configuration
*/
@CheckReturnValue
public Splitter trimResults() {
return trimResults(CharMatcher.WHITESPACE);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* removes all leading or trailing characters matching the given {@code
* CharMatcher} from each returned substring. For example, {@code
* Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")}
* returns an iterable containing {@code ["a ", "b_ ", "c"]}.
*
* @param trimmer a {@link CharMatcher} that determines whether a character
* should be removed from the beginning/end of a subsequence
* @return a splitter with the desired configuration
*/
// TODO(kevinb): throw if a trimmer was already specified!
@CheckReturnValue
public Splitter trimResults(CharMatcher trimmer) {
checkNotNull(trimmer);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
/**
* Splits {@code sequence} into string components and makes them available
* through an {@link Iterator}, which may be lazily evaluated. If you want
* an eagerly computed {@link List}, use {@link #splitToList(CharSequence)}.
*
* @param sequence the sequence of characters to split
* @return an iteration over the segments split from the parameter.
*/
public Iterable<String> split(final CharSequence sequence) {
checkNotNull(sequence);
return new Iterable<String>() {
@Override public Iterator<String> iterator() {
return spliterator(sequence);
}
@Override public String toString() {
return Joiner.on(", ")
.appendTo(new StringBuilder().append('['), this)
.append(']')
.toString();
}
};
}
private Iterator<String> spliterator(CharSequence sequence) {
return strategy.iterator(this, sequence);
}
/**
* Splits {@code sequence} into string components and returns them as
* an immutable list. If you want an {@link Iterable} which may be lazily
* evaluated, use {@link #split(CharSequence)}.
*
* @param sequence the sequence of characters to split
* @return an immutable list of the segments split from the parameter
* @since 15.0
*/
@Beta
public List<String> splitToList(CharSequence sequence) {
checkNotNull(sequence);
Iterator<String> iterator = spliterator(sequence);
List<String> result = new ArrayList<String>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
return Collections.unmodifiableList(result);
}
/**
* Returns a {@code MapSplitter} which splits entries based on this splitter,
* and splits entries into keys and values using the specified separator.
*
* @since 10.0
*/
@CheckReturnValue
@Beta
public MapSplitter withKeyValueSeparator(String separator) {
return withKeyValueSeparator(on(separator));
}
/**
* Returns a {@code MapSplitter} which splits entries based on this splitter,
* and splits entries into keys and values using the specified separator.
*
* @since 14.0
*/
@CheckReturnValue
@Beta
public MapSplitter withKeyValueSeparator(char separator) {
return withKeyValueSeparator(on(separator));
}
/**
* Returns a {@code MapSplitter} which splits entries based on this splitter,
* and splits entries into keys and values using the specified key-value
* splitter.
*
* @since 10.0
*/
@CheckReturnValue
@Beta
public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
return new MapSplitter(this, keyValueSplitter);
}
/**
* An object that splits strings into maps as {@code Splitter} splits
* iterables and lists. Like {@code Splitter}, it is thread-safe and
* immutable.
*
* @since 10.0
*/
@Beta
public static final class MapSplitter {
private static final String INVALID_ENTRY_MESSAGE =
"Chunk [%s] is not a valid entry";
private final Splitter outerSplitter;
private final Splitter entrySplitter;
private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) {
this.outerSplitter = outerSplitter; // only "this" is passed
this.entrySplitter = checkNotNull(entrySplitter);
}
/**
* Splits {@code sequence} into substrings, splits each substring into
* an entry, and returns an unmodifiable map with each of the entries. For
* example, <code>
* Splitter.on(';').trimResults().withKeyValueSeparator("=>")
* .split("a=>b ; c=>b")
* </code> will return a mapping from {@code "a"} to {@code "b"} and
* {@code "c"} to {@code b}.
*
* <p>The returned map preserves the order of the entries from
* {@code sequence}.
*
* @throws IllegalArgumentException if the specified sequence does not split
* into valid map entries, or if there are duplicate keys
*/
public Map<String, String> split(CharSequence sequence) {
Map<String, String> map = new LinkedHashMap<String, String>();
for (String entry : outerSplitter.split(sequence)) {
Iterator<String> entryFields = entrySplitter.spliterator(entry);
checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
String key = entryFields.next();
checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
String value = entryFields.next();
map.put(key, value);
checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
}
return Collections.unmodifiableMap(map);
}
}
private interface Strategy {
Iterator<String> iterator(Splitter splitter, CharSequence toSplit);
}
private abstract static class SplittingIterator extends AbstractIterator<String> {
final CharSequence toSplit;
final CharMatcher trimmer;
final boolean omitEmptyStrings;
/**
* Returns the first index in {@code toSplit} at or after {@code start}
* that contains the separator.
*/
abstract int separatorStart(int start);
/**
* Returns the first index in {@code toSplit} after {@code
* separatorPosition} that does not contain a separator. This method is only
* invoked after a call to {@code separatorStart}.
*/
abstract int separatorEnd(int separatorPosition);
int offset = 0;
int limit;
protected SplittingIterator(Splitter splitter, CharSequence toSplit) {
this.trimmer = splitter.trimmer;
this.omitEmptyStrings = splitter.omitEmptyStrings;
this.limit = splitter.limit;
this.toSplit = toSplit;
}
@Override protected String computeNext() {
/*
* The returned string will be from the end of the last match to the
* beginning of the next one. nextStart is the start position of the
* returned substring, while offset is the place to start looking for a
* separator.
*/
int nextStart = offset;
while (offset != -1) {
int start = nextStart;
int end;
int separatorPosition = separatorStart(offset);
if (separatorPosition == -1) {
end = toSplit.length();
offset = -1;
} else {
end = separatorPosition;
offset = separatorEnd(separatorPosition);
}
if (offset == nextStart) {
/*
* This occurs when some pattern has an empty match, even if it
* doesn't match the empty string -- for example, if it requires
* lookahead or the like. The offset must be increased to look for
* separators beyond this point, without changing the start position
* of the next returned substring -- so nextStart stays the same.
*/
offset++;
if (offset >= toSplit.length()) {
offset = -1;
}
continue;
}
while (start < end && trimmer.matches(toSplit.charAt(start))) {
start++;
}
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
if (omitEmptyStrings && start == end) {
// Don't include the (unused) separator in next split string.
nextStart = offset;
continue;
}
if (limit == 1) {
// The limit has been reached, return the rest of the string as the
// final item. This is tested after empty string removal so that
// empty strings do not count towards the limit.
end = toSplit.length();
offset = -1;
// Since we may have changed the end, we need to trim it again.
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
} else {
limit--;
}
return toSplit.subSequence(start, end).toString();
}
return endOfData();
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import javax.annotation.CheckReturnValue;
/**
* Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does
* for any {@link Object}. Also offers basic text processing methods based on this function.
* Implementations are strongly encouraged to be side-effect-free and immutable.
*
* <p>Throughout the documentation of this class, the phrase "matching character" is used to mean
* "any character {@code c} for which {@code this.matches(c)} returns {@code true}".
*
* <p><b>Note:</b> This class deals only with {@code char} values; it does not understand
* supplementary Unicode code points in the range {@code 0x10000} to {@code 0x10FFFF}. Such logical
* characters are encoded into a {@code String} using surrogate pairs, and a {@code CharMatcher}
* treats these just as two separate characters.
*
* <p>Example usages: <pre>
* String trimmed = {@link #WHITESPACE WHITESPACE}.{@link #trimFrom trimFrom}(userInput);
* if ({@link #ASCII ASCII}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre>
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher">
* {@code CharMatcher}</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta // Possibly change from chars to code points; decide constants vs. methods
@GwtCompatible(emulated = true)
public abstract class CharMatcher implements Predicate<Character> {
// Constants
/**
* Determines whether a character is a breaking whitespace (that is, a whitespace which can be
* interpreted as a break between words for formatting purposes). See {@link #WHITESPACE} for a
* discussion of that term.
*
* @since 2.0
*/
public static final CharMatcher BREAKING_WHITESPACE = new CharMatcher() {
@Override
public boolean matches(char c) {
switch (c) {
case '\t':
case '\n':
case '\013':
case '\f':
case '\r':
case ' ':
case '\u0085':
case '\u1680':
case '\u2028':
case '\u2029':
case '\u205f':
case '\u3000':
return true;
case '\u2007':
return false;
default:
return c >= '\u2000' && c <= '\u200a';
}
}
@Override
public String toString() {
return "CharMatcher.BREAKING_WHITESPACE";
}
};
/**
* Determines whether a character is ASCII, meaning that its code point is less than 128.
*/
public static final CharMatcher ASCII = inRange('\0', '\u007f', "CharMatcher.ASCII");
private static class RangesMatcher extends CharMatcher {
private final char[] rangeStarts;
private final char[] rangeEnds;
RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) {
super(description);
this.rangeStarts = rangeStarts;
this.rangeEnds = rangeEnds;
checkArgument(rangeStarts.length == rangeEnds.length);
for (int i = 0; i < rangeStarts.length; i++) {
checkArgument(rangeStarts[i] <= rangeEnds[i]);
if (i + 1 < rangeStarts.length) {
checkArgument(rangeEnds[i] < rangeStarts[i + 1]);
}
}
}
@Override
public boolean matches(char c) {
int index = Arrays.binarySearch(rangeStarts, c);
if (index >= 0) {
return true;
} else {
index = ~index - 1;
return index >= 0 && c <= rangeEnds[index];
}
}
}
// Must be in ascending order.
private static final String ZEROES = "0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6"
+ "\u0c66\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946\u19d0\u1b50\u1bb0"
+ "\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10";
private static final String NINES;
static {
StringBuilder builder = new StringBuilder(ZEROES.length());
for (int i = 0; i < ZEROES.length(); i++) {
builder.append((char) (ZEROES.charAt(i) + 9));
}
NINES = builder.toString();
}
/**
* Determines whether a character is a digit according to
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>.
*/
public static final CharMatcher DIGIT = new RangesMatcher(
"CharMatcher.DIGIT", ZEROES.toCharArray(), NINES.toCharArray());
/**
* Determines whether a character is a digit according to {@link Character#isDigit(char) Java's
* definition}. If you only care to match ASCII digits, you can use {@code inRange('0', '9')}.
*/
public static final CharMatcher JAVA_DIGIT = new CharMatcher("CharMatcher.JAVA_DIGIT") {
@Override public boolean matches(char c) {
return Character.isDigit(c);
}
};
/**
* Determines whether a character is a letter according to {@link Character#isLetter(char) Java's
* definition}. If you only care to match letters of the Latin alphabet, you can use {@code
* inRange('a', 'z').or(inRange('A', 'Z'))}.
*/
public static final CharMatcher JAVA_LETTER = new CharMatcher("CharMatcher.JAVA_LETTER") {
@Override public boolean matches(char c) {
return Character.isLetter(c);
}
};
/**
* Determines whether a character is a letter or digit according to {@link
* Character#isLetterOrDigit(char) Java's definition}.
*/
public static final CharMatcher JAVA_LETTER_OR_DIGIT =
new CharMatcher("CharMatcher.JAVA_LETTER_OR_DIGIT") {
@Override public boolean matches(char c) {
return Character.isLetterOrDigit(c);
}
};
/**
* Determines whether a character is upper case according to {@link Character#isUpperCase(char)
* Java's definition}.
*/
public static final CharMatcher JAVA_UPPER_CASE =
new CharMatcher("CharMatcher.JAVA_UPPER_CASE") {
@Override public boolean matches(char c) {
return Character.isUpperCase(c);
}
};
/**
* Determines whether a character is lower case according to {@link Character#isLowerCase(char)
* Java's definition}.
*/
public static final CharMatcher JAVA_LOWER_CASE =
new CharMatcher("CharMatcher.JAVA_LOWER_CASE") {
@Override public boolean matches(char c) {
return Character.isLowerCase(c);
}
};
/**
* Determines whether a character is an ISO control character as specified by {@link
* Character#isISOControl(char)}.
*/
public static final CharMatcher JAVA_ISO_CONTROL =
inRange('\u0000', '\u001f')
.or(inRange('\u007f', '\u009f'))
.withToString("CharMatcher.JAVA_ISO_CONTROL");
/**
* Determines whether a character is invisible; that is, if its Unicode category is any of
* SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and
* PRIVATE_USE according to ICU4J.
*/
public static final CharMatcher INVISIBLE = new RangesMatcher("CharMatcher.INVISIBLE", (
"\u0000\u007f\u00ad\u0600\u06dd\u070f\u1680\u180e\u2000\u2028\u205f\u206a\u3000\ud800\ufeff"
+ "\ufff9\ufffa").toCharArray(), (
"\u0020\u00a0\u00ad\u0604\u06dd\u070f\u1680\u180e\u200f\u202f\u2064\u206f\u3000\uf8ff\ufeff"
+ "\ufff9\ufffb").toCharArray());
private static String showCharacter(char c) {
String hex = "0123456789ABCDEF";
char[] tmp = {'\\', 'u', '\0', '\0', '\0', '\0'};
for (int i = 0; i < 4; i++) {
tmp[5 - i] = hex.charAt(c & 0xF);
c >>= 4;
}
return String.copyValueOf(tmp);
}
/**
* Determines whether a character is single-width (not double-width). When in doubt, this matcher
* errs on the side of returning {@code false} (that is, it tends to assume a character is
* double-width).
*
* <p><b>Note:</b> as the reference file evolves, we will modify this constant to keep it up to
* date.
*/
public static final CharMatcher SINGLE_WIDTH = new RangesMatcher("CharMatcher.SINGLE_WIDTH",
"\u0000\u05be\u05d0\u05f3\u0600\u0750\u0e00\u1e00\u2100\ufb50\ufe70\uff61".toCharArray(),
"\u04f9\u05be\u05ea\u05f4\u06ff\u077f\u0e7f\u20af\u213a\ufdff\ufeff\uffdc".toCharArray());
/** Matches any character. */
public static final CharMatcher ANY =
new FastMatcher("CharMatcher.ANY") {
@Override public boolean matches(char c) {
return true;
}
@Override public int indexIn(CharSequence sequence) {
return (sequence.length() == 0) ? -1 : 0;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return (start == length) ? -1 : start;
}
@Override public int lastIndexIn(CharSequence sequence) {
return sequence.length() - 1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
checkNotNull(sequence);
return true;
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
return sequence.length() == 0;
}
@Override public String removeFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
char[] array = new char[sequence.length()];
Arrays.fill(array, replacement);
return new String(array);
}
@Override public String replaceFrom(CharSequence sequence, CharSequence replacement) {
StringBuilder retval = new StringBuilder(sequence.length() * replacement.length());
for (int i = 0; i < sequence.length(); i++) {
retval.append(replacement);
}
return retval.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return (sequence.length() == 0) ? "" : String.valueOf(replacement);
}
@Override public String trimFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public int countIn(CharSequence sequence) {
return sequence.length();
}
@Override public CharMatcher and(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher or(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher negate() {
return NONE;
}
};
/** Matches no characters. */
public static final CharMatcher NONE =
new FastMatcher("CharMatcher.NONE") {
@Override public boolean matches(char c) {
return false;
}
@Override public int indexIn(CharSequence sequence) {
checkNotNull(sequence);
return -1;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return -1;
}
@Override public int lastIndexIn(CharSequence sequence) {
checkNotNull(sequence);
return -1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return sequence.length() == 0;
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
checkNotNull(sequence);
return true;
}
@Override public String removeFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
return sequence.toString();
}
@Override public String replaceFrom(CharSequence sequence, CharSequence replacement) {
checkNotNull(replacement);
return sequence.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return sequence.toString();
}
@Override public String trimFrom(CharSequence sequence) {
return sequence.toString();
}
@Override
public String trimLeadingFrom(CharSequence sequence) {
return sequence.toString();
}
@Override
public String trimTrailingFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public int countIn(CharSequence sequence) {
checkNotNull(sequence);
return 0;
}
@Override public CharMatcher and(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher or(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher negate() {
return ANY;
}
};
// Static factories
/**
* Returns a {@code char} matcher that matches only one specified character.
*/
public static CharMatcher is(final char match) {
String description = "CharMatcher.is('" + showCharacter(match) + "')";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c == match;
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
return sequence.toString().replace(match, replacement);
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? this : NONE;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? other : super.or(other);
}
@Override public CharMatcher negate() {
return isNot(match);
}
};
}
/**
* Returns a {@code char} matcher that matches any character except the one specified.
*
* <p>To negate another {@code CharMatcher}, use {@link #negate()}.
*/
public static CharMatcher isNot(final char match) {
String description = "CharMatcher.isNot(" + Integer.toHexString(match) + ")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c != match;
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? super.and(other) : other;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? ANY : this;
}
@Override public CharMatcher negate() {
return is(match);
}
};
}
/**
* Returns a {@code char} matcher that matches any character present in the given character
* sequence.
*/
public static CharMatcher anyOf(final CharSequence sequence) {
switch (sequence.length()) {
case 0:
return NONE;
case 1:
return is(sequence.charAt(0));
case 2:
return isEither(sequence.charAt(0), sequence.charAt(1));
default:
// continue below to handle the general case
}
// TODO(user): is it potentially worth just going ahead and building a precomputed matcher?
final char[] chars = sequence.toString().toCharArray();
Arrays.sort(chars);
StringBuilder description = new StringBuilder("CharMatcher.anyOf(\"");
for (char c : chars) {
description.append(showCharacter(c));
}
description.append("\")");
return new CharMatcher(description.toString()) {
@Override public boolean matches(char c) {
return Arrays.binarySearch(chars, c) >= 0;
}
};
}
private static CharMatcher isEither(
final char match1,
final char match2) {
String description = "CharMatcher.anyOf(\"" +
showCharacter(match1) + showCharacter(match2) + "\")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c == match1 || c == match2;
}
};
}
/**
* Returns a {@code char} matcher that matches any character not present in the given character
* sequence.
*/
public static CharMatcher noneOf(CharSequence sequence) {
return anyOf(sequence).negate();
}
/**
* Returns a {@code char} matcher that matches any character in a given range (both endpoints are
* inclusive). For example, to match any lowercase letter of the English alphabet, use {@code
* CharMatcher.inRange('a', 'z')}.
*
* @throws IllegalArgumentException if {@code endInclusive < startInclusive}
*/
public static CharMatcher inRange(final char startInclusive, final char endInclusive) {
checkArgument(endInclusive >= startInclusive);
String description = "CharMatcher.inRange('" +
showCharacter(startInclusive) + "', '" +
showCharacter(endInclusive) + "')";
return inRange(startInclusive, endInclusive, description);
}
static CharMatcher inRange(final char startInclusive, final char endInclusive,
String description) {
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return startInclusive <= c && c <= endInclusive;
}
};
}
/**
* Returns a matcher with identical behavior to the given {@link Character}-based predicate, but
* which operates on primitive {@code char} instances instead.
*/
public static CharMatcher forPredicate(final Predicate<? super Character> predicate) {
checkNotNull(predicate);
if (predicate instanceof CharMatcher) {
return (CharMatcher) predicate;
}
String description = "CharMatcher.forPredicate(" + predicate + ")";
return new CharMatcher(description) {
@Override public boolean matches(char c) {
return predicate.apply(c);
}
@Override public boolean apply(Character character) {
return predicate.apply(checkNotNull(character));
}
};
}
// State
final String description;
// Constructors
/**
* Sets the {@code toString()} from the given description.
*/
CharMatcher(String description) {
this.description = description;
}
/**
* Constructor for use by subclasses. When subclassing, you may want to override
* {@code toString()} to provide a useful description.
*/
protected CharMatcher() {
description = super.toString();
}
// Abstract methods
/** Determines a true or false value for the given character. */
public abstract boolean matches(char c);
// Non-static factories
/**
* Returns a matcher that matches any character not matched by this matcher.
*/
public CharMatcher negate() {
return new NegatedMatcher(this);
}
private static class NegatedMatcher extends CharMatcher {
final CharMatcher original;
NegatedMatcher(String toString, CharMatcher original) {
super(toString);
this.original = original;
}
NegatedMatcher(CharMatcher original) {
this(original + ".negate()", original);
}
@Override public boolean matches(char c) {
return !original.matches(c);
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return original.matchesNoneOf(sequence);
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
return original.matchesAllOf(sequence);
}
@Override public int countIn(CharSequence sequence) {
return sequence.length() - original.countIn(sequence);
}
@Override public CharMatcher negate() {
return original;
}
@Override
CharMatcher withToString(String description) {
return new NegatedMatcher(description, original);
}
}
/**
* Returns a matcher that matches any character matched by both this matcher and {@code other}.
*/
public CharMatcher and(CharMatcher other) {
return new And(this, checkNotNull(other));
}
private static class And extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
And(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.and(" + a + ", " + b + ")");
}
And(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
@Override
public boolean matches(char c) {
return first.matches(c) && second.matches(c);
}
@Override
CharMatcher withToString(String description) {
return new And(first, second, description);
}
}
/**
* Returns a matcher that matches any character matched by either this matcher or {@code other}.
*/
public CharMatcher or(CharMatcher other) {
return new Or(this, checkNotNull(other));
}
private static class Or extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
Or(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
Or(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.or(" + a + ", " + b + ")");
}
@Override
public boolean matches(char c) {
return first.matches(c) || second.matches(c);
}
@Override
CharMatcher withToString(String description) {
return new Or(first, second, description);
}
}
/**
* Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to
* query than the original; your mileage may vary. Precomputation takes time and is likely to be
* worthwhile only if the precomputed matcher is queried many thousands of times.
*
* <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a
* precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a
* worthwhile tradeoff in a browser.
*/
public CharMatcher precomputed() {
return Platform.precomputeCharMatcher(this);
}
/**
* Subclasses should provide a new CharMatcher with the same characteristics as {@code this},
* but with their {@code toString} method overridden with the new description.
*
* <p>This is unsupported by default.
*/
CharMatcher withToString(String description) {
throw new UnsupportedOperationException();
}
private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1;
/**
* A matcher for which precomputation will not yield any significant benefit.
*/
abstract static class FastMatcher extends CharMatcher {
FastMatcher() {
super();
}
FastMatcher(String description) {
super(description);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
public CharMatcher negate() {
return new NegatedFastMatcher(this);
}
}
static final class NegatedFastMatcher extends NegatedMatcher {
NegatedFastMatcher(CharMatcher original) {
super(original);
}
NegatedFastMatcher(String toString, CharMatcher original) {
super(toString, original);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
CharMatcher withToString(String description) {
return new NegatedFastMatcher(description, original);
}
}
private static boolean isSmall(int totalCharacters, int tableLength) {
return totalCharacters <= SmallCharMatcher.MAX_SIZE
&& tableLength > (totalCharacters * 4 * Character.SIZE);
// err on the side of BitSetMatcher
}
// Text processing routines
/**
* Returns {@code true} if a character sequence contains at least one matching character.
* Equivalent to {@code !matchesNoneOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code true} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches at least one character in the sequence
* @since 8.0
*/
public boolean matchesAnyOf(CharSequence sequence) {
return !matchesNoneOf(sequence);
}
/**
* Returns {@code true} if a character sequence contains only matching characters.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesAllOf(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (!matches(sequence.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if a character sequence contains no matching characters. Equivalent to
* {@code !matchesAnyOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesNoneOf(CharSequence sequence) {
return indexIn(sequence) == -1;
}
/**
* Returns the index of the first matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in forward order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the beginning
* @return an index, or {@code -1} if no character matches
*/
public int indexIn(CharSequence sequence) {
int length = sequence.length();
for (int i = 0; i < length; i++) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the index of the first matching character in a character sequence, starting from a
* given position, or {@code -1} if no character matches after that position.
*
* <p>The default implementation iterates over the sequence in forward order, beginning at {@code
* start}, calling {@link #matches} for each character.
*
* @param sequence the character sequence to examine
* @param start the first index to examine; must be nonnegative and no greater than {@code
* sequence.length()}
* @return the index of the first matching character, guaranteed to be no less than {@code start},
* or {@code -1} if no character matches
* @throws IndexOutOfBoundsException if start is negative or greater than {@code
* sequence.length()}
*/
public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
for (int i = start; i < length; i++) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the index of the last matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in reverse order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the end
* @return an index, or {@code -1} if no character matches
*/
public int lastIndexIn(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the number of matching characters found in a character sequence.
*/
public int countIn(CharSequence sequence) {
int count = 0;
for (int i = 0; i < sequence.length(); i++) {
if (matches(sequence.charAt(i))) {
count++;
}
}
return count;
}
/**
* Returns a string containing all non-matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').removeFrom("bazaar")}</pre>
*
* ... returns {@code "bzr"}.
*/
@CheckReturnValue
public String removeFrom(CharSequence sequence) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
int spread = 1;
// This unusual loop comes from extensive benchmarking
OUT: while (true) {
pos++;
while (true) {
if (pos == chars.length) {
break OUT;
}
if (matches(chars[pos])) {
break;
}
chars[pos - spread] = chars[pos];
pos++;
}
spread++;
}
return new String(chars, 0, pos - spread);
}
/**
* Returns a string containing all matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').retainFrom("bazaar")}</pre>
*
* ... returns {@code "aaa"}.
*/
@CheckReturnValue
public String retainFrom(CharSequence sequence) {
return negate().removeFrom(sequence);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement character. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("radar", 'o')}</pre>
*
* ... returns {@code "rodor"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the character to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, char replacement) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
chars[pos] = replacement;
for (int i = pos + 1; i < chars.length; i++) {
if (matches(chars[i])) {
chars[i] = replacement;
}
}
return new String(chars);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement sequence. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("yaha", "oo")}</pre>
*
* ... returns {@code "yoohoo"}.
*
* <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better
* off calling {@link #replaceFrom(CharSequence, char)} directly.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the characters to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, CharSequence replacement) {
int replacementLen = replacement.length();
if (replacementLen == 0) {
return removeFrom(sequence);
}
if (replacementLen == 1) {
return replaceFrom(sequence, replacement.charAt(0));
}
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
int len = string.length();
StringBuilder buf = new StringBuilder((len * 3 / 2) + 16);
int oldpos = 0;
do {
buf.append(string, oldpos, pos);
buf.append(replacement);
oldpos = pos + 1;
pos = indexIn(string, oldpos);
} while (pos != -1);
buf.append(string, oldpos, len);
return buf.toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning and from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimFrom("abacatbab")}</pre>
*
* ... returns {@code "cat"}.
*
* <p>Note that: <pre> {@code
*
* CharMatcher.inRange('\0', ' ').trimFrom(str)}</pre>
*
* ... is equivalent to {@link String#trim()}.
*/
@CheckReturnValue
public String trimFrom(CharSequence sequence) {
int len = sequence.length();
int first;
int last;
for (first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
break;
}
}
for (last = len - 1; last > first; last--) {
if (!matches(sequence.charAt(last))) {
break;
}
}
return sequence.subSequence(first, last + 1).toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}</pre>
*
* ... returns {@code "catbab"}.
*/
@CheckReturnValue
public String trimLeadingFrom(CharSequence sequence) {
int len = sequence.length();
for (int first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
return sequence.subSequence(first, len).toString();
}
}
return "";
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}</pre>
*
* ... returns {@code "abacat"}.
*/
@CheckReturnValue
public String trimTrailingFrom(CharSequence sequence) {
int len = sequence.length();
for (int last = len - 1; last >= 0; last--) {
if (!matches(sequence.charAt(last))) {
return sequence.subSequence(0, last + 1).toString();
}
}
return "";
}
/**
* Returns a string copy of the input character sequence, with each group of consecutive
* characters that match this matcher replaced by a single replacement character. For example:
* <pre> {@code
*
* CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}</pre>
*
* ... returns {@code "b-p-r"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching groups of characters in
* @param replacement the character to append to the result string in place of each group of
* matching characters in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String collapseFrom(CharSequence sequence, char replacement) {
// This implementation avoids unnecessary allocation.
int len = sequence.length();
for (int i = 0; i < len; i++) {
char c = sequence.charAt(i);
if (matches(c)) {
if (c == replacement
&& (i == len - 1 || !matches(sequence.charAt(i + 1)))) {
// a no-op replacement
i++;
} else {
StringBuilder builder = new StringBuilder(len)
.append(sequence.subSequence(0, i))
.append(replacement);
return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true);
}
}
}
// no replacement needed
return sequence.toString();
}
/**
* Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that
* groups of matching characters at the start or end of the sequence are removed without
* replacement.
*/
@CheckReturnValue
public String trimAndCollapseFrom(CharSequence sequence, char replacement) {
// This implementation avoids unnecessary allocation.
int len = sequence.length();
int first;
int last;
for (first = 0; first < len && matches(sequence.charAt(first)); first++) {}
for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) {}
return (first == 0 && last == len - 1)
? collapseFrom(sequence, replacement)
: finishCollapseFrom(
sequence, first, last + 1, replacement,
new StringBuilder(last + 1 - first),
false);
}
private String finishCollapseFrom(
CharSequence sequence, int start, int end, char replacement,
StringBuilder builder, boolean inMatchingGroup) {
for (int i = start; i < end; i++) {
char c = sequence.charAt(i);
if (matches(c)) {
if (!inMatchingGroup) {
builder.append(replacement);
inMatchingGroup = true;
}
} else {
builder.append(c);
inMatchingGroup = false;
}
}
return builder.toString();
}
// Predicate interface
/**
* Equivalent to {@link #matches}; provided only to satisfy the {@link Predicate} interface. When
* using a reference of type {@code CharMatcher}, invoke {@link #matches} directly instead.
*/
@Override public boolean apply(Character character) {
return matches(character);
}
/**
* Returns a string representation of this {@code CharMatcher}, such as
* {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}.
*/
@Override
public String toString() {
return description;
}
/**
* A special-case CharMatcher for Unicode whitespace characters that is extremely
* efficient both in space required and in time to check for matches.
*
* Implementation details.
* It turns out that all current (early 2012) Unicode characters are unique modulo 79:
* so we can construct a lookup table of exactly 79 entries, and just check the character code
* mod 79, and see if that character is in the table.
*
* There is a 1 at the beginning of the table so that the null character is not listed
* as whitespace.
*
* Other things we tried that did not prove to be beneficial, mostly due to speed concerns:
*
* * Binary search into the sorted list of characters, i.e., what
* CharMatcher.anyOf() does</li>
* * Perfect hash function into a table of size 26 (using an offset table and a special
* Jenkins hash function)</li>
* * Perfect-ish hash function that required two lookups into a single table of size 26.</li>
* * Using a power-of-2 sized hash table (size 64) with linear probing.</li>
*
* --Christopher Swenson, February 2012.
*/
private static final String WHITESPACE_TABLE = "\u0001\u0000\u00a0\u0000\u0000\u0000\u0000\u0000"
+ "\u0000\u0009\n\u000b\u000c\r\u0000\u0000\u2028\u2029\u0000\u0000\u0000\u0000\u0000\u202f"
+ "\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0020\u0000\u0000\u0000\u0000\u0000"
+ "\u0000\u0000\u0000\u0000\u0000\u3000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
+ "\u0000\u0000\u0085\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
+ "\u0000\u0000\u0000\u0000\u0000\u205f\u1680\u0000\u0000\u180e\u0000\u0000\u0000";
/**
* Determines whether a character is whitespace according to the latest Unicode standard, as
* illustrated
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>.
* This is not the same definition used by other Java APIs. (See a
* <a href="http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ">comparison of several
* definitions of "whitespace"</a>.)
*
* <p><b>Note:</b> as the Unicode definition evolves, we will modify this constant to keep it up
* to date.
*/
public static final CharMatcher WHITESPACE = new FastMatcher("CharMatcher.WHITESPACE") {
@Override public boolean matches(char c) {
return WHITESPACE_TABLE.charAt(c % 79) == c;
}
};
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import java.nio.charset.Charset;
/**
* Contains constant definitions for the six standard {@link Charset} instances, which are
* guaranteed to be supported by all Java platform implementations.
*
* <p>Assuming you're free to choose, note that <b>{@link #UTF_8} is widely preferred</b>.
*
* <p>See the Guava User Guide article on <a
* href="http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets">
* {@code Charsets}</a>.
*
* @author Mike Bostock
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Charsets {
private Charsets() {}
/**
* UTF-8: eight-bit UCS Transformation Format.
*/
public static final Charset UTF_8 = Charset.forName("UTF-8");
/*
* Please do not add new Charset references to this class, unless those character encodings are
* part of the set required to be supported by all Java platform implementations! Any Charsets
* initialized here may cause unexpected delays when this class is loaded. See the Charset
* Javadocs for the list of built-in character encodings.
*/
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code int} primitives, that are not
* already found in either {@link Integer} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Ints {
private Ints() {}
/**
* The number of bytes required to represent a primitive {@code int}
* value.
*/
public static final int BYTES = Integer.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as an {@code int}.
*
* @since 10.0
*/
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Integer) value).hashCode()}.
*
* @param value a primitive {@code int} value
* @return a hash code for the value
*/
public static int hashCode(int value) {
return value;
}
/**
* Returns the {@code int} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code int} type
* @return the {@code int} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE}
*/
public static int checkedCast(long value) {
int result = (int) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the
* {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
* or {@link Integer#MIN_VALUE} if it is too small
*/
public static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
/**
* Compares the two specified {@code int} values. The sign of the value
* returned is the same as that of {@code ((Integer) a).compareTo(b)}.
*
* @param a the first {@code int} to compare
* @param b the second {@code int} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(int a, int b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(int[] array, int target) {
for (int value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(int[] array, int target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
int[] array, int target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(int[] array, int[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(int[] array, int target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
int[] array, int target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code int} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int min(int... array) {
checkArgument(array.length > 0);
int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code int} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int max(int... array) {
checkArgument(array.length > 0);
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new int[] {a, b}, new int[] {}, new
* int[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code int} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
int[] result = new int[length];
int pos = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static int[] ensureCapacity(
int[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static int[] copyOf(int[] original, int length) {
int[] copy = new int[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code int} values separated
* by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns
* the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code int} values, possibly empty
*/
public static String join(String separator, int... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code int} arrays
* lexicographically. That is, it compares, using {@link
* #compare(int, int)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(int[], int[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<int[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<int[]> {
INSTANCE;
@Override
public int compare(int[] left, int[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Ints.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code int} value in the manner of {@link Number#intValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
*/
public static int[] toArray(Collection<? extends Number> collection) {
if (collection instanceof IntArrayAsList) {
return ((IntArrayAsList) collection).toIntArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
int[] array = new int[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Integer} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Integer> asList(int... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new IntArrayAsList(backingArray);
}
@GwtCompatible
private static class IntArrayAsList extends AbstractList<Integer>
implements RandomAccess, Serializable {
final int[] array;
final int start;
final int end;
IntArrayAsList(int[] array) {
this(array, 0, array.length);
}
IntArrayAsList(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Integer get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Integer)
&& Ints.indexOf(array, (Integer) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.indexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.lastIndexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Integer set(int index, Integer element) {
checkElementIndex(index, size());
int oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Integer> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new IntArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof IntArrayAsList) {
IntArrayAsList that = (IntArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Ints.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
int[] toIntArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
int[] result = new int[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code char} primitives, that are not
* already found in either {@link Character} or {@link Arrays}.
*
* <p>All the operations in this class treat {@code char} values strictly
* numerically; they are neither Unicode-aware nor locale-dependent.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Chars {
private Chars() {}
/**
* The number of bytes required to represent a primitive {@code char}
* value.
*/
public static final int BYTES = Character.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Character) value).hashCode()}.
*
* @param value a primitive {@code char} value
* @return a hash code for the value
*/
public static int hashCode(char value) {
return value;
}
/**
* Returns the {@code char} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code char} type
* @return the {@code char} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Character#MAX_VALUE} or less than {@link Character#MIN_VALUE}
*/
public static char checkedCast(long value) {
char result = (char) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code char} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code char} if it is in the range of the
* {@code char} type, {@link Character#MAX_VALUE} if it is too large,
* or {@link Character#MIN_VALUE} if it is too small
*/
public static char saturatedCast(long value) {
if (value > Character.MAX_VALUE) {
return Character.MAX_VALUE;
}
if (value < Character.MIN_VALUE) {
return Character.MIN_VALUE;
}
return (char) value;
}
/**
* Compares the two specified {@code char} values. The sign of the value
* returned is the same as that of {@code ((Character) a).compareTo(b)}.
*
* @param a the first {@code char} to compare
* @param b the second {@code char} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(char a, char b) {
return a - b; // safe due to restricted range
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(char[] array, char target) {
for (char value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(char[] array, char target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
char[] array, char target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(char[] array, char[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(char[] array, char target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
char[] array, char target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code char} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static char min(char... array) {
checkArgument(array.length > 0);
char min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code char} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static char max(char... array) {
checkArgument(array.length > 0);
char max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new char[] {a, b}, new char[] {}, new
* char[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code char} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static char[] concat(char[]... arrays) {
int length = 0;
for (char[] array : arrays) {
length += array.length;
}
char[] result = new char[length];
int pos = 0;
for (char[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static char[] ensureCapacity(
char[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static char[] copyOf(char[] original, int length) {
char[] copy = new char[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code char} values separated
* by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns
* the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code char} values, possibly empty
*/
public static String join(String separator, char... array) {
checkNotNull(separator);
int len = array.length;
if (len == 0) {
return "";
}
StringBuilder builder
= new StringBuilder(len + separator.length() * (len - 1));
builder.append(array[0]);
for (int i = 1; i < len; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code char} arrays
* lexicographically. That is, it compares, using {@link
* #compare(char, char)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < ['a'] < ['a', 'b'] < ['b']}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(char[], char[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<char[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<char[]> {
INSTANCE;
@Override
public int compare(char[] left, char[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Chars.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Copies a collection of {@code Character} instances into a new array of
* primitive {@code char} values.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Character} objects
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
*/
public static char[] toArray(Collection<Character> collection) {
if (collection instanceof CharArrayAsList) {
return ((CharArrayAsList) collection).toCharArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
char[] array = new char[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = (Character) checkNotNull(boxedArray[i]);
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Character} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Character> asList(char... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new CharArrayAsList(backingArray);
}
@GwtCompatible
private static class CharArrayAsList extends AbstractList<Character>
implements RandomAccess, Serializable {
final char[] array;
final int start;
final int end;
CharArrayAsList(char[] array) {
this(array, 0, array.length);
}
CharArrayAsList(char[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Character)
&& Chars.indexOf(array, (Character) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Character) {
int i = Chars.indexOf(array, (Character) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Character) {
int i = Chars.lastIndexOf(array, (Character) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Character set(int index, Character element) {
checkElementIndex(index, size());
char oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Character> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new CharArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof CharArrayAsList) {
CharArrayAsList that = (CharArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Chars.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 3);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
char[] toCharArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
char[] result = new char[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code short} primitives, that are not
* already found in either {@link Short} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Shorts {
private Shorts() {}
/**
* The number of bytes required to represent a primitive {@code short}
* value.
*/
public static final int BYTES = Short.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as a {@code short}.
*
* @since 10.0
*/
public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Short) value).hashCode()}.
*
* @param value a primitive {@code short} value
* @return a hash code for the value
*/
public static int hashCode(short value) {
return value;
}
/**
* Returns the {@code short} value that is equal to {@code value}, if
* possible.
*
* @param value any value in the range of the {@code short} type
* @return the {@code short} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Short#MAX_VALUE} or less than {@link Short#MIN_VALUE}
*/
public static short checkedCast(long value) {
short result = (short) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code short} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code short} if it is in the range of the
* {@code short} type, {@link Short#MAX_VALUE} if it is too large,
* or {@link Short#MIN_VALUE} if it is too small
*/
public static short saturatedCast(long value) {
if (value > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
if (value < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
return (short) value;
}
/**
* Compares the two specified {@code short} values. The sign of the value
* returned is the same as that of {@code ((Short) a).compareTo(b)}.
*
* @param a the first {@code short} to compare
* @param b the second {@code short} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(short a, short b) {
return a - b; // safe due to restricted range
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(short[] array, short target) {
for (short value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(short[] array, short target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
short[] array, short target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(short[] array, short[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(short[] array, short target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
short[] array, short target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code short} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static short min(short... array) {
checkArgument(array.length > 0);
short min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code short} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static short max(short... array) {
checkArgument(array.length > 0);
short max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new short[] {a, b}, new short[] {}, new
* short[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code short} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static short[] concat(short[]... arrays) {
int length = 0;
for (short[] array : arrays) {
length += array.length;
}
short[] result = new short[length];
int pos = 0;
for (short[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static short[] ensureCapacity(
short[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static short[] copyOf(short[] original, int length) {
short[] copy = new short[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code short} values separated
* by {@code separator}. For example, {@code join("-", (short) 1, (short) 2,
* (short) 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code short} values, possibly empty
*/
public static String join(String separator, short... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 6);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code short} arrays
* lexicographically. That is, it compares, using {@link
* #compare(short, short)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [(short) 1] <
* [(short) 1, (short) 2] < [(short) 2]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(short[], short[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<short[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<short[]> {
INSTANCE;
@Override
public int compare(short[] left, short[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Shorts.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code short} value in the manner of {@link Number#shortValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
*/
public static short[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ShortArrayAsList) {
return ((ShortArrayAsList) collection).toShortArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
short[] array = new short[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Short} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Short> asList(short... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ShortArrayAsList(backingArray);
}
@GwtCompatible
private static class ShortArrayAsList extends AbstractList<Short>
implements RandomAccess, Serializable {
final short[] array;
final int start;
final int end;
ShortArrayAsList(short[] array) {
this(array, 0, array.length);
}
ShortArrayAsList(short[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Short get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Short)
&& Shorts.indexOf(array, (Short) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.indexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.lastIndexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Short set(int index, Short element) {
checkElementIndex(index, size());
short oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Short> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof ShortArrayAsList) {
ShortArrayAsList that = (ShortArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Shorts.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 6);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
short[] toShortArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
short[] result = new short[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code double} primitives, that are not
* already found in either {@link Double} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Doubles {
private Doubles() {}
/**
* The number of bytes required to represent a primitive {@code double}
* value.
*
* @since 10.0
*/
public static final int BYTES = Double.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Double) value).hashCode()}.
*
* @param value a primitive {@code double} value
* @return a hash code for the value
*/
public static int hashCode(double value) {
return ((Double) value).hashCode();
// TODO(kevinb): do it this way when we can (GWT problem):
// long bits = Double.doubleToLongBits(value);
// return (int) (bits ^ (bits >>> 32));
}
/**
* Compares the two specified {@code double} values. The sign of the value
* returned is the same as that of <code>((Double) a).{@linkplain
* Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is
* treated as greater than all other values, and {@code 0.0 > -0.0}.
*
* @param a the first {@code double} to compare
* @param b the second {@code double} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(double a, double b) {
return Double.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(double value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(double[] array, double target) {
for (double value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(double[] array, double target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
double[] array, double target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(double[] array, double[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(double[] array, double target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
double[] array, double target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}, using the same rules of
* comparison as {@link Math#min(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static double min(double... array) {
checkArgument(array.length > 0);
double min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#max(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static double max(double... array) {
checkArgument(array.length > 0);
double max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new double[] {a, b}, new double[] {}, new
* double[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code double} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static double[] concat(double[]... arrays) {
int length = 0;
for (double[] array : arrays) {
length += array.length;
}
double[] result = new double[length];
int pos = 0;
for (double[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static double[] ensureCapacity(
double[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static double[] copyOf(double[] original, int length) {
double[] copy = new double[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code double} values, converted
* to strings as specified by {@link Double#toString(double)}, and separated
* by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns
* the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Double#toString(double)} formats {@code double}
* differently in GWT sometimes. In the previous example, it returns the
* string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code double} values, possibly empty
*/
public static String join(String separator, double... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code double} arrays
* lexicographically. That is, it compares, using {@link
* #compare(double, double)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(double[], double[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<double[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<double[]> {
INSTANCE;
@Override
public int compare(double[] left, double[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Doubles.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code double} value in the manner of {@link Number#doubleValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
*/
public static double[] toArray(Collection<? extends Number> collection) {
if (collection instanceof DoubleArrayAsList) {
return ((DoubleArrayAsList) collection).toDoubleArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
double[] array = new double[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Double} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Double> asList(double... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new DoubleArrayAsList(backingArray);
}
@GwtCompatible
private static class DoubleArrayAsList extends AbstractList<Double>
implements RandomAccess, Serializable {
final double[] array;
final int start;
final int end;
DoubleArrayAsList(double[] array) {
this(array, 0, array.length);
}
DoubleArrayAsList(double[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Double get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Double)
&& Doubles.indexOf(array, (Double) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.indexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.lastIndexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Double set(int index, Double element) {
checkElementIndex(index, size());
double oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Double> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof DoubleArrayAsList) {
DoubleArrayAsList that = (DoubleArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Doubles.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
double[] toDoubleArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
double[] result = new double[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.primitives.UnsignedInts.INT_MASK;
import static com.google.common.primitives.UnsignedInts.compare;
import static com.google.common.primitives.UnsignedInts.toLong;
import com.google.common.annotations.GwtCompatible;
import java.math.BigInteger;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* A wrapper class for unsigned {@code int} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> {
public static final UnsignedInteger ZERO = fromIntBits(0);
public static final UnsignedInteger ONE = fromIntBits(1);
public static final UnsignedInteger MAX_VALUE = fromIntBits(-1);
private final int value;
private UnsignedInteger(int value) {
// GWT doesn't consistently overflow values to make them 32-bit, so we need to force it.
this.value = value & 0xffffffff;
}
/**
* Returns an {@code UnsignedInteger} corresponding to a given bit representation.
* The argument is interpreted as an unsigned 32-bit value. Specifically, the sign bit
* of {@code bits} is interpreted as a normal bit, and all other bits are treated as usual.
*
* <p>If the argument is nonnegative, the returned result will be equal to {@code bits},
* otherwise, the result will be equal to {@code 2^32 + bits}.
*
* <p>To represent unsigned decimal constants, consider {@link #valueOf(long)} instead.
*
* @since 14.0
*/
public static UnsignedInteger fromIntBits(int bits) {
return new UnsignedInteger(bits);
}
/**
* Returns an {@code UnsignedInteger} that is equal to {@code value},
* if possible. The inverse operation of {@link #longValue()}.
*/
public static UnsignedInteger valueOf(long value) {
checkArgument((value & INT_MASK) == value,
"value (%s) is outside the range for an unsigned integer value", value);
return fromIntBits((int) value);
}
/**
* Returns a {@code UnsignedInteger} representing the same value as the specified
* {@link BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
*
* @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32}
*/
public static UnsignedInteger valueOf(BigInteger value) {
checkNotNull(value);
checkArgument(value.signum() >= 0 && value.bitLength() <= Integer.SIZE,
"value (%s) is outside the range for an unsigned integer value", value);
return fromIntBits(value.intValue());
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string) {
return valueOf(string, 10);
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value in the specified radix.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string, int radix) {
return fromIntBits(UnsignedInts.parseUnsignedInt(string, radix));
}
/**
* Returns the result of adding this and {@code val}. If the result would have more than 32 bits,
* returns the low 32 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger plus(UnsignedInteger val) {
return fromIntBits(this.value + checkNotNull(val).value);
}
/**
* Returns the result of subtracting this and {@code val}. If the result would be negative,
* returns the low 32 bits of the result.
*
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger minus(UnsignedInteger val) {
return fromIntBits(value - checkNotNull(val).value);
}
/**
* Returns the result of dividing this by {@code val}.
*
* @throws ArithmeticException if {@code val} is zero
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger dividedBy(UnsignedInteger val) {
return fromIntBits(UnsignedInts.divide(value, checkNotNull(val).value));
}
/**
* Returns this mod {@code val}.
*
* @throws ArithmeticException if {@code val} is zero
* @since 14.0
*/
@CheckReturnValue
public UnsignedInteger mod(UnsignedInteger val) {
return fromIntBits(UnsignedInts.remainder(value, checkNotNull(val).value));
}
/**
* Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse
* operation to {@link #fromIntBits}.
*
* <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value
* will be equal to {@code this - 2^32}.
*/
@Override
public int intValue() {
return value;
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code long}.
*/
@Override
public long longValue() {
return toLong(value);
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code float}, and correctly rounded.
*/
@Override
public float floatValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code double}, and correctly rounded.
*/
@Override
public double doubleValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}.
*/
public BigInteger bigIntegerValue() {
return BigInteger.valueOf(longValue());
}
/**
* Compares this unsigned integer to another unsigned integer.
* Returns {@code 0} if they are equal, a negative number if {@code this < other},
* and a positive number if {@code this > other}.
*/
@Override
public int compareTo(UnsignedInteger other) {
checkNotNull(other);
return compare(value, other.value);
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof UnsignedInteger) {
UnsignedInteger other = (UnsignedInteger) obj;
return value == other.value;
}
return false;
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base 10.
*/
@Override
public String toString() {
return toString(10);
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}.
* If {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix
* {@code 10} is used.
*/
public String toString(int radix) {
return UnsignedInts.toString(value, radix);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.POSITIVE_INFINITY;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code float} primitives, that are not
* already found in either {@link Float} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Floats {
private Floats() {}
/**
* The number of bytes required to represent a primitive {@code float}
* value.
*
* @since 10.0
*/
public static final int BYTES = Float.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Float) value).hashCode()}.
*
* @param value a primitive {@code float} value
* @return a hash code for the value
*/
public static int hashCode(float value) {
// TODO(kevinb): is there a better way, that's still gwt-safe?
return ((Float) value).hashCode();
}
/**
* Compares the two specified {@code float} values using {@link
* Float#compare(float, float)}. You may prefer to invoke that method
* directly; this method exists only for consistency with the other utilities
* in this package.
*
* @param a the first {@code float} to compare
* @param b the second {@code float} to compare
* @return the result of invoking {@link Float#compare(float, float)}
*/
public static int compare(float a, float b) {
return Float.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Float.isInfinite(value) || Float.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(float value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(float[] array, float target) {
for (float value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(float[] array, float target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
float[] array, float target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(float[] array, float[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(float[] array, float target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
float[] array, float target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}, using the same rules of
* comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static float min(float... array) {
checkArgument(array.length > 0);
float min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static float max(float... array) {
checkArgument(array.length > 0);
float max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new float[] {a, b}, new float[] {}, new
* float[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code float} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static float[] concat(float[]... arrays) {
int length = 0;
for (float[] array : arrays) {
length += array.length;
}
float[] result = new float[length];
int pos = 0;
for (float[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static float[] ensureCapacity(
float[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static float[] copyOf(float[] original, int length) {
float[] copy = new float[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code float} values, converted
* to strings as specified by {@link Float#toString(float)}, and separated by
* {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)}
* returns the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Float#toString(float)} formats {@code float}
* differently in GWT. In the previous example, it returns the string {@code
* "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code float} values, possibly empty
*/
public static String join(String separator, float... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code float} arrays
* lexicographically. That is, it compares, using {@link
* #compare(float, float)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f]
* < [2.0f]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(float[], float[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<float[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<float[]> {
INSTANCE;
@Override
public int compare(float[] left, float[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Floats.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code float} value in the manner of {@link Number#floatValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Float>} before 12.0)
*/
public static float[] toArray(Collection<? extends Number> collection) {
if (collection instanceof FloatArrayAsList) {
return ((FloatArrayAsList) collection).toFloatArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
float[] array = new float[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Float} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Float> asList(float... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new FloatArrayAsList(backingArray);
}
@GwtCompatible
private static class FloatArrayAsList extends AbstractList<Float>
implements RandomAccess, Serializable {
final float[] array;
final int start;
final int end;
FloatArrayAsList(float[] array) {
this(array, 0, array.length);
}
FloatArrayAsList(float[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Float get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Float)
&& Floats.indexOf(array, (Float) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.indexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.lastIndexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Float set(int index, Float element) {
checkElementIndex(index, size());
float oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Float> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new FloatArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof FloatArrayAsList) {
FloatArrayAsList that = (FloatArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Floats.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
float[] toFloatArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
float[] result = new float[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in
* {@link IntMath} and {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(
SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, or {@code 1} if {@code n == 0}.
*
* <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial
* with balanced multiplies. It also removes all the 2s from the intermediate
* products (shifting them back in at the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.factorials.length) {
return BigInteger.valueOf(LongMath.factorials[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.factorials.length;
long product = LongMath.factorials[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum = accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
private BigIntegerMath() {}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in
* {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code long} values, see {@link com.google.common.primitives.Longs}.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class LongMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Long.bitCount(x) == 1}, because
* {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a
* signed long. The implementation is branch-free, and benchmarks suggest it is measurably
* faster than the straightforward ternary expression.
*/
@VisibleForTesting
static int lessThanBranchFree(long x, long y) {
// Returns the sign bit of x - y.
return (int) (~~(x - y) >>> (Long.SIZE - 1));
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(long x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Long.numberOfLeadingZeros(x);
long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
default:
throw new AssertionError("impossible");
}
}
/** The biggest half power of two that fits into an unsigned long */
@VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
// maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {
19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4,
3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };
// halfPowersOf10[i] = largest long less than 10^(i + 0.5)
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static long gcd(long a, long b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't
* an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >60% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Long.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Long.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
long delta = a - b; // can't overflow, since a and b are nonnegative
long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
@VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
static final long[] factorials = {
1L,
1L,
1L * 2,
1L * 2 * 3,
1L * 2 * 3 * 4,
1L * 2 * 3 * 4 * 5,
1L * 2 * 3 * 4 * 5 * 6,
1L * 2 * 3 * 4 * 5 * 6 * 7,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static long binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
if (n < factorials.length) {
return factorials[n] / (factorials[k] * factorials[n - k]);
} else if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
return Long.MAX_VALUE;
} else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) {
// guaranteed not to overflow
long result = n--;
for (int i = 2; i <= k; n--, i++) {
result *= n;
result /= i;
}
return result;
} else {
int nBits = LongMath.log2(n, RoundingMode.CEILING);
long result = 1;
long numerator = n--;
long denominator = 1;
int numeratorBits = nBits;
// This is an upper bound on log2(numerator, ceiling).
/*
* We want to do this in long math for speed, but want to avoid overflow. We adapt the
* technique previously used by BigIntegerMath: maintain separate numerator and
* denominator accumulators, multiplying the fraction into result when near overflow.
*/
for (int i = 2; i <= k; i++, n--) {
if (numeratorBits + nBits < Long.SIZE - 1) {
// It's definitely safe to multiply into numerator and denominator.
numerator *= n;
denominator *= i;
numeratorBits += nBits;
} else {
// It might not be safe to multiply into numerator and denominator,
// so multiply (numerator / denominator) into result.
result = multiplyFraction(result, numerator, denominator);
numerator = n;
denominator = i;
numeratorBits = nBits;
}
}
return multiplyFraction(result, numerator, denominator);
}
}
}
/**
* Returns (x * numerator / denominator), which is assumed to come out to an integral value.
*/
static long multiplyFraction(long x, long numerator, long denominator) {
if (x == 1) {
return numerator / denominator;
}
long commonDivisor = gcd(x, denominator);
x /= commonDivisor;
denominator /= commonDivisor;
// We know gcd(x, denominator) = 1, and x * numerator / denominator is exact,
// so denominator must be a divisor of numerator.
return x * (numerator / denominator);
}
/*
* binomial(biggestBinomials[k], k) fits in a long, but not
* binomial(biggestBinomials[k] + 1, k).
*/
static final int[] biggestBinomials =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
67, 67, 66, 66, 66, 66};
/*
* binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl,
* but binomial(biggestSimpleBinomials[k] + 1, k) does.
*/
@VisibleForTesting static final int[] biggestSimpleBinomials =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
61, 61, 61};
// These values were generated by using checkedMultiply to see when the simple multiply/divide
// algorithm would lead to an overflow.
static boolean fitsInInt(long x) {
return (int) x == x;
}
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
* negative infinity. This method is resilient to overflow.
*
* @since 14.0
*/
public static long mean(long x, long y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private LongMath() {}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.math;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in
* {@link LongMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code int} values, see {@link com.google.common.primitives.Ints}.
*
* @author Louis Wasserman
* @since 11.0
*/
@GwtCompatible(emulated = true)
public final class IntMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Integer.bitCount(x) == 1}, because
* {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
* of two.
*/
public static boolean isPowerOfTwo(int x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into
* a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if
* narrowly) faster than the straightforward ternary expression.
*/
@VisibleForTesting
static int lessThanBranchFree(int x, int y) {
// The double negation is optimized away by normal Java, but is necessary for GWT
// to make sure bit twiddling works as expected.
return ~~(x - y) >>> (Integer.SIZE - 1);
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
// TODO(kevinb): remove after this warning is disabled globally
public static int log2(int x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Integer.numberOfLeadingZeros(x);
int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Integer.SIZE - 1) - leadingZeros;
return logFloor + lessThanBranchFree(cmp, x);
default:
throw new AssertionError();
}
}
/** The biggest half power of two that can fit in an unsigned int. */
@VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
private static int log10Floor(int x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)];
/*
* y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
* lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - lessThanBranchFree(x, powersOf10[y]);
}
// maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {9, 9, 9, 8, 8, 8,
7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0};
@VisibleForTesting static final int[] powersOf10 = {1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000};
// halfPowersOf10[i] = largest int less than 10^(i + 0.5)
@VisibleForTesting static final int[] halfPowersOf10 =
{3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
private static int sqrtFloor(int x) {
// There is no loss of precision in converting an int to a double, according to
// http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
return (int) Math.sqrt(x);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@SuppressWarnings("fallthrough")
public static int divide(int p, int q, RoundingMode mode) {
checkNotNull(mode);
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:<pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
public static int mod(int x, int m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
int result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static int gcd(int a, int b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
* isn't an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >40% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Integer.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
int delta = a - b; // can't overflow, since a and b are nonnegative
int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
*/
public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
*/
public static int checkedSubtract(int a, int b) {
long result = (long) a - b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
*/
public static int checkedMultiply(int a, int b) {
long result = (long) a * b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* <p>{@link #pow} may be faster, but does not check for overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code int} arithmetic
*/
public static int checkedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Integer.SIZE - 1);
return 1 << k;
case (-2):
checkNoOverflow(k < Integer.SIZE);
return ((k & 1) == 0) ? 1 << k : -1 << k;
default:
// continue below to handle the general case
}
int accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
b *= b;
}
}
}
}
@VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
* result does not fit in a {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static int factorial(int n) {
checkNonNegative("n", n);
return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE;
}
private static final int[] factorials = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
// binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k).
@VisibleForTesting static int[] biggestBinomials = {
Integer.MAX_VALUE,
Integer.MAX_VALUE,
65536,
2345,
477,
193,
110,
75,
58,
49,
43,
39,
37,
35,
34,
34,
33
};
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
* negative infinity. This method is overflow resilient.
*
* @since 14.0
*/
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private IntMath() {}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.escape;
/**
* @author Jesse Wilson
*/
class Platform {
private static final char[] CHAR_BUFFER = new char[1024];
static char[] charBufferFromThreadLocal() {
// ThreadLocal is not available to GWT, so we always reuse the same
// instance. It is always safe to return the same instance because
// javascript is single-threaded, and only used by blocks that doesn't
// involve async callbacks.
return CHAR_BUFFER;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtCompatible
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] newArray(T[] reference, int length) {
return Array.createFrom(reference, length);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
/**
* GWT emulation of {@link ImmutableEnumMap}. The type parameter is not bounded
* by {@code Enum<E>} to avoid code-size bloat.
*
* @author Hayward Chan
*/
final class ImmutableEnumMap<K, V> extends ForwardingImmutableMap<K, V> {
static <K, V> ImmutableMap<K, V> asImmutable(Map<K, V> map) {
for (Map.Entry<K, V> entry : checkNotNull(map).entrySet()) {
checkNotNull(entry.getKey());
checkNotNull(entry.getValue());
}
return new ImmutableEnumMap<K, V>(map);
}
ImmutableEnumMap(Map<? extends K, ? extends V> delegate) {
super(WellBehavedMap.wrap(delegate));
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Set;
/**
* GWT emulation of {@link ImmutableEnumSet}. The type parameter is not bounded
* by {@code Enum<E>} to avoid code-size bloat.
*
* @author Hayward Chan
*/
final class ImmutableEnumSet<E> extends ForwardingImmutableSet<E> {
static <E> ImmutableSet<E> asImmutable(Set<E> delegate) {
switch (delegate.size()) {
case 0:
return ImmutableSet.of();
case 1:
return ImmutableSet.of(Iterables.getOnlyElement(delegate));
default:
return new ImmutableEnumSet<E>(delegate);
}
}
public ImmutableEnumSet(Set<E> delegate) {
super(delegate);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collections;
/**
* GWT emulation of {@link EmptyImmutableSet}.
*
* @author Hayward Chan
*/
final class EmptyImmutableSet extends ForwardingImmutableSet<Object> {
private EmptyImmutableSet() {
super(Collections.emptySet());
}
static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet();
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* GWT emulated version of {@link ImmutableCollection}.
*
* @author Jesse Wilson
*/
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableCollection<E> extends AbstractCollection<E>
implements Serializable {
static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION
= new ForwardingImmutableCollection<Object>(Collections.emptyList());
ImmutableCollection() {}
public abstract UnmodifiableIterator<E> iterator();
public boolean contains(@Nullable Object object) {
return object != null && super.contains(object);
}
public final boolean add(E e) {
throw new UnsupportedOperationException();
}
public final boolean remove(Object object) {
throw new UnsupportedOperationException();
}
public final boolean addAll(Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
public final boolean removeAll(Collection<?> oldElements) {
throw new UnsupportedOperationException();
}
public final boolean retainAll(Collection<?> elementsToKeep) {
throw new UnsupportedOperationException();
}
public final void clear() {
throw new UnsupportedOperationException();
}
private transient ImmutableList<E> asList;
public ImmutableList<E> asList() {
ImmutableList<E> list = asList;
return (list == null) ? (asList = createAsList()) : list;
}
ImmutableList<E> createAsList() {
switch (size()) {
case 0:
return ImmutableList.of();
case 1:
return ImmutableList.of(iterator().next());
default:
return new RegularImmutableAsList<E>(this, toArray());
}
}
static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) {
return new ForwardingImmutableCollection<E>(delegate);
}
boolean isPartialView() {
return false;
}
abstract static class Builder<E> {
public abstract Builder<E> add(E element);
public Builder<E> add(E... elements) {
checkNotNull(elements); // for GWT
for (E element : elements) {
add(checkNotNull(element));
}
return this;
}
public Builder<E> addAll(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
for (E element : elements) {
add(checkNotNull(element));
}
return this;
}
public Builder<E> addAll(Iterator<? extends E> elements) {
checkNotNull(elements); // for GWT
while (elements.hasNext()) {
add(checkNotNull(elements.next()));
}
return this;
}
public abstract ImmutableCollection<E> build();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
/**
* GWT emulation of {@link RegularImmutableBiMap}.
*
* @author Jared Levy
* @author Hayward Chan
*/
@SuppressWarnings("serial")
class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
// This reference is used both by the GWT compiler to infer the elements
// of the lists that needs to be serialized.
private ImmutableBiMap<V, K> inverse;
RegularImmutableBiMap(ImmutableMap<K, V> delegate) {
super(delegate);
ImmutableMap.Builder<V, K> builder = ImmutableMap.builder();
for (Entry<K, V> entry : delegate.entrySet()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableMap<V, K> backwardMap = builder.build();
this.inverse = new RegularImmutableBiMap<V, K>(backwardMap, this);
}
RegularImmutableBiMap(ImmutableMap<K, V> delegate,
ImmutableBiMap<V, K> inverse) {
super(delegate);
this.inverse = inverse;
}
@Override public ImmutableBiMap<V, K> inverse() {
return inverse;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.collect.BoundType.CLOSED;
import static com.google.common.collect.BoundType.OPEN;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset.Entry;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static utility methods for creating and working with
* {@link SortedMultiset} instances.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
final class SortedMultisets {
private SortedMultisets() {
}
/**
* A skeleton implementation for {@link SortedMultiset#elementSet}.
*/
static class ElementSet<E> extends Multisets.ElementSet<E> implements
SortedSet<E> {
private final SortedMultiset<E> multiset;
ElementSet(SortedMultiset<E> multiset) {
this.multiset = multiset;
}
@Override final SortedMultiset<E> multiset() {
return multiset;
}
@Override public Comparator<? super E> comparator() {
return multiset().comparator();
}
@Override public SortedSet<E> subSet(E fromElement, E toElement) {
return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet();
}
@Override public SortedSet<E> headSet(E toElement) {
return multiset().headMultiset(toElement, OPEN).elementSet();
}
@Override public SortedSet<E> tailSet(E fromElement) {
return multiset().tailMultiset(fromElement, CLOSED).elementSet();
}
@Override public E first() {
return getElementOrThrow(multiset().firstEntry());
}
@Override public E last() {
return getElementOrThrow(multiset().lastEntry());
}
}
private static <E> E getElementOrThrow(Entry<E> entry) {
if (entry == null) {
throw new NoSuchElementException();
}
return entry.getElement();
}
private static <E> E getElementOrNull(@Nullable Entry<E> entry) {
return (entry == null) ? null : entry.getElement();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Optional;
import java.util.LinkedList;
import java.util.Iterator;
/**
* A variant of {@link TreeTraverser} for binary trees, providing additional traversals specific to
* binary trees.
*
* @author Louis Wasserman
*/
public abstract class BinaryTreeTraverser<T> extends TreeTraverser<T> {
// TODO(user): make this GWT-compatible when we've checked in ArrayDeque and BitSet emulation
/**
* Returns the left child of the specified node, or {@link Optional#absent()} if the specified
* node has no left child.
*/
public abstract Optional<T> leftChild(T root);
/**
* Returns the right child of the specified node, or {@link Optional#absent()} if the specified
* node has no right child.
*/
public abstract Optional<T> rightChild(T root);
/**
* Returns the children of this node, in left-to-right order.
*/
@Override
public final Iterable<T> children(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return new AbstractIterator<T>() {
boolean doneLeft;
boolean doneRight;
@Override
protected T computeNext() {
if (!doneLeft) {
doneLeft = true;
Optional<T> left = leftChild(root);
if (left.isPresent()) {
return left.get();
}
}
if (!doneRight) {
doneRight = true;
Optional<T> right = rightChild(root);
if (right.isPresent()) {
return right.get();
}
}
return endOfData();
}
};
}
};
}
// TODO(user): see if any significant optimizations are possible for breadthFirstIterator
public final FluentIterable<T> inOrderTraversal(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public UnmodifiableIterator<T> iterator() {
return new InOrderIterator(root);
}
};
}
private static final class InOrderNode<T> {
final T node;
boolean hasExpandedLeft;
InOrderNode(T node) {
this.node = checkNotNull(node);
this.hasExpandedLeft = false;
}
}
private final class InOrderIterator extends AbstractIterator<T> {
private final LinkedList<InOrderNode<T>> stack;
InOrderIterator(T root) {
this.stack = Lists.newLinkedList();
stack.addLast(new InOrderNode<T>(root));
}
@Override
protected T computeNext() {
while (!stack.isEmpty()) {
InOrderNode<T> inOrderNode = stack.getLast();
if (inOrderNode.hasExpandedLeft) {
stack.removeLast();
pushIfPresent(rightChild(inOrderNode.node));
return inOrderNode.node;
} else {
inOrderNode.hasExpandedLeft = true;
pushIfPresent(leftChild(inOrderNode.node));
}
}
return endOfData();
}
private void pushIfPresent(Optional<T> node) {
if (node.isPresent()) {
stack.addLast(new InOrderNode<T>(node.get()));
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* A GWT-only class only used by GWT emulations. It is used to consolidate the
* definitions of method delegation to save code size.
*
* @author Hayward Chan
*/
// TODO: Make this class GWT serializable.
class ForwardingImmutableCollection<E> extends ImmutableCollection<E> {
transient final Collection<E> delegate;
ForwardingImmutableCollection(Collection<E> delegate) {
this.delegate = delegate;
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override public boolean contains(@Nullable Object object) {
return object != null && delegate.contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return delegate.containsAll(targets);
}
public int size() {
return delegate.size();
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public Object[] toArray() {
return delegate.toArray();
}
@Override public <T> T[] toArray(T[] other) {
return delegate.toArray(other);
}
@Override public String toString() {
return delegate.toString();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
/**
* GWT emulation of {@link SingletonImmutableBiMap}.
*
* @author Hayward Chan
*/
final class SingletonImmutableBiMap<K, V> extends ImmutableBiMap<K, V> {
// These references are used both by the custom field serializer, and by the
// GWT compiler to infer the keys and values of the map that needs to be
// serialized.
//
// Although they are non-final, they are package private and the reference is
// never modified after a map is constructed.
K singleKey;
V singleValue;
transient SingletonImmutableBiMap<V, K> inverse;
SingletonImmutableBiMap(K key, V value) {
super(Collections.singletonMap(checkNotNull(key), checkNotNull(value)));
this.singleKey = key;
this.singleValue = value;
}
private SingletonImmutableBiMap(
K key, V value, SingletonImmutableBiMap<V, K> inverse) {
super(Collections.singletonMap(checkNotNull(key), checkNotNull(value)));
this.singleKey = key;
this.singleValue = value;
this.inverse = inverse;
}
@Override
public ImmutableBiMap<V, K> inverse() {
ImmutableBiMap<V, K> result = inverse;
if (result == null) {
return inverse = new SingletonImmutableBiMap<V, K>(singleValue, singleKey, this);
} else {
return result;
}
}
@Override
public ImmutableSet<V> values() {
return ImmutableSet.of(singleValue);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Maps.ImprovedAbstractMap;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link Multimap} interface. This class represents
* a multimap as a map that associates each key with a collection of values. All
* methods of {@link Multimap} are supported, including those specified as
* optional in the interface.
*
* <p>To implement a multimap, a subclass must define the method {@link
* #createCollection()}, which creates an empty collection of values for a key.
*
* <p>The multimap constructor takes a map that has a single entry for each
* distinct key. When you insert a key-value pair with a key that isn't already
* in the multimap, {@code AbstractMapBasedMultimap} calls {@link #createCollection()}
* to create the collection of values for that key. The subclass should not call
* {@link #createCollection()} directly, and a new instance should be created
* every time the method is called.
*
* <p>For example, the subclass could pass a {@link java.util.TreeMap} during
* construction, and {@link #createCollection()} could return a {@link
* java.util.TreeSet}, in which case the multimap's iterators would propagate
* through the keys and values in sorted order.
*
* <p>Keys and values may be null, as long as the underlying collection classes
* support null elements.
*
* <p>The collections created by {@link #createCollection()} may or may not
* allow duplicates. If the collection, such as a {@link Set}, does not support
* duplicates, an added key-value pair will replace an existing pair with the
* same key and value, if such a pair is present. With collections like {@link
* List} that allow duplicates, the collection will keep the existing key-value
* pairs while adding a new pair.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap, even if the underlying map and {@link #createCollection()} method
* return threadsafe classes. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedMultimap}.
*
* <p>For serialization to work, the subclass must specify explicit
* {@code readObject} and {@code writeObject} methods.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultimap<K, V> extends AbstractMultimap<K, V>
implements Serializable {
/*
* Here's an outline of the overall design.
*
* The map variable contains the collection of values associated with each
* key. When a key-value pair is added to a multimap that didn't previously
* contain any values for that key, a new collection generated by
* createCollection is added to the map. That same collection instance
* remains in the map as long as the multimap has any values for the key. If
* all values for the key are removed, the key and collection are removed
* from the map.
*
* The get method returns a WrappedCollection, which decorates the collection
* in the map (if the key is present) or an empty collection (if the key is
* not present). When the collection delegate in the WrappedCollection is
* empty, the multimap may contain subsequently added values for that key. To
* handle that situation, the WrappedCollection checks whether map contains
* an entry for the provided key, and if so replaces the delegate.
*/
private transient Map<K, Collection<V>> map;
private transient int totalSize;
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @throws IllegalArgumentException if {@code map} is not empty
*/
protected AbstractMapBasedMultimap(Map<K, Collection<V>> map) {
checkArgument(map.isEmpty());
this.map = map;
}
/** Used during deserialization only. */
final void setMap(Map<K, Collection<V>> map) {
this.map = map;
totalSize = 0;
for (Collection<V> values : map.values()) {
checkArgument(!values.isEmpty());
totalSize += values.size();
}
}
/**
* Creates an unmodifiable, empty collection of values.
*
* <p>This is used in {@link #removeAll} on an empty key.
*/
Collection<V> createUnmodifiableEmptyCollection() {
return unmodifiableCollectionSubclass(createCollection());
}
/**
* Creates the collection of values for a single key.
*
* <p>Collections with weak, soft, or phantom references are not supported.
* Each call to {@code createCollection} should create a new instance.
*
* <p>The returned collection class determines whether duplicate key-value
* pairs are allowed.
*
* @return an empty collection of values
*/
abstract Collection<V> createCollection();
/**
* Creates the collection of values for an explicitly provided key. By
* default, it simply calls {@link #createCollection()}, which is the correct
* behavior for most implementations. The {@link LinkedHashMultimap} class
* overrides it.
*
* @param key key to associate with values in the collection
* @return an empty collection of values
*/
Collection<V> createCollection(@Nullable K key) {
return createCollection();
}
Map<K, Collection<V>> backingMap() {
return map;
}
// Query Operations
@Override
public int size() {
return totalSize;
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
// Modification Operations
@Override
public boolean put(@Nullable K key, @Nullable V value) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
if (collection.add(value)) {
totalSize++;
map.put(key, collection);
return true;
} else {
throw new AssertionError("New Collection violated the Collection spec");
}
} else if (collection.add(value)) {
totalSize++;
return true;
} else {
return false;
}
}
private Collection<V> getOrCreateCollection(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
map.put(key, collection);
}
return collection;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
Iterator<? extends V> iterator = values.iterator();
if (!iterator.hasNext()) {
return removeAll(key);
}
// TODO(user): investigate atomic failure?
Collection<V> collection = getOrCreateCollection(key);
Collection<V> oldValues = createCollection();
oldValues.addAll(collection);
totalSize -= collection.size();
collection.clear();
while (iterator.hasNext()) {
if (collection.add(iterator.next())) {
totalSize++;
}
}
return unmodifiableCollectionSubclass(oldValues);
}
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/
@Override
public Collection<V> removeAll(@Nullable Object key) {
Collection<V> collection = map.remove(key);
if (collection == null) {
return createUnmodifiableEmptyCollection();
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return unmodifiableCollectionSubclass(output);
}
Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
} else {
return Collections.unmodifiableCollection(collection);
}
}
@Override
public void clear() {
// Clear each collection, to make previously returned collections empty.
for (Collection<V> collection : map.values()) {
collection.clear();
}
map.clear();
totalSize = 0;
}
// Views
/**
* {@inheritDoc}
*
* <p>The returned collection is not serializable.
*/
@Override
public Collection<V> get(@Nullable K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createCollection(key);
}
return wrapCollection(key, collection);
}
/**
* Generates a decorated collection that remains consistent with the values in
* the multimap for the provided key. Changes to the multimap may alter the
* returned collection, and vice versa.
*/
Collection<V> wrapCollection(@Nullable K key, Collection<V> collection) {
// We don't deal with NavigableSet here yet for GWT reasons -- instead,
// non-GWT TreeMultimap explicitly overrides this and uses NavigableSet.
if (collection instanceof SortedSet) {
return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
} else if (collection instanceof Set) {
return new WrappedSet(key, (Set<V>) collection);
} else if (collection instanceof List) {
return wrapList(key, (List<V>) collection, null);
} else {
return new WrappedCollection(key, collection, null);
}
}
private List<V> wrapList(
@Nullable K key, List<V> list, @Nullable WrappedCollection ancestor) {
return (list instanceof RandomAccess)
? new RandomAccessWrappedList(key, list, ancestor)
: new WrappedList(key, list, ancestor);
}
/**
* Collection decorator that stays in sync with the multimap values for a key.
* There are two kinds of wrapped collections: full and subcollections. Both
* have a delegate pointing to the underlying collection class.
*
* <p>Full collections, identified by a null ancestor field, contain all
* multimap values for a given key. Its delegate is a value in {@link
* AbstractMapBasedMultimap#map} whenever the delegate is non-empty. The {@code
* refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure
* that the {@code WrappedCollection} and map remain consistent.
*
* <p>A subcollection, such as a sublist, contains some of the values for a
* given key. Its ancestor field points to the full wrapped collection with
* all values for the key. The subcollection {@code refreshIfEmpty}, {@code
* removeIfEmpty}, and {@code addToMap} methods call the corresponding methods
* of the full wrapped collection.
*/
private class WrappedCollection extends AbstractCollection<V> {
final K key;
Collection<V> delegate;
final WrappedCollection ancestor;
final Collection<V> ancestorDelegate;
WrappedCollection(@Nullable K key, Collection<V> delegate,
@Nullable WrappedCollection ancestor) {
this.key = key;
this.delegate = delegate;
this.ancestor = ancestor;
this.ancestorDelegate
= (ancestor == null) ? null : ancestor.getDelegate();
}
/**
* If the delegate collection is empty, but the multimap has values for the
* key, replace the delegate with the new collection for the key.
*
* <p>For a subcollection, refresh its ancestor and validate that the
* ancestor delegate hasn't changed.
*/
void refreshIfEmpty() {
if (ancestor != null) {
ancestor.refreshIfEmpty();
if (ancestor.getDelegate() != ancestorDelegate) {
throw new ConcurrentModificationException();
}
} else if (delegate.isEmpty()) {
Collection<V> newDelegate = map.get(key);
if (newDelegate != null) {
delegate = newDelegate;
}
}
}
/**
* If collection is empty, remove it from {@code AbstractMapBasedMultimap.this.map}.
* For subcollections, check whether the ancestor collection is empty.
*/
void removeIfEmpty() {
if (ancestor != null) {
ancestor.removeIfEmpty();
} else if (delegate.isEmpty()) {
map.remove(key);
}
}
K getKey() {
return key;
}
/**
* Add the delegate to the map. Other {@code WrappedCollection} methods
* should call this method after adding elements to a previously empty
* collection.
*
* <p>Subcollection add the ancestor's delegate instead.
*/
void addToMap() {
if (ancestor != null) {
ancestor.addToMap();
} else {
map.put(key, delegate);
}
}
@Override public int size() {
refreshIfEmpty();
return delegate.size();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
refreshIfEmpty();
return delegate.equals(object);
}
@Override public int hashCode() {
refreshIfEmpty();
return delegate.hashCode();
}
@Override public String toString() {
refreshIfEmpty();
return delegate.toString();
}
Collection<V> getDelegate() {
return delegate;
}
@Override public Iterator<V> iterator() {
refreshIfEmpty();
return new WrappedIterator();
}
/** Collection iterator for {@code WrappedCollection}. */
class WrappedIterator implements Iterator<V> {
final Iterator<V> delegateIterator;
final Collection<V> originalDelegate = delegate;
WrappedIterator() {
delegateIterator = iteratorOrListIterator(delegate);
}
WrappedIterator(Iterator<V> delegateIterator) {
this.delegateIterator = delegateIterator;
}
/**
* If the delegate changed since the iterator was created, the iterator is
* no longer valid.
*/
void validateIterator() {
refreshIfEmpty();
if (delegate != originalDelegate) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
validateIterator();
return delegateIterator.hasNext();
}
@Override
public V next() {
validateIterator();
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
totalSize--;
removeIfEmpty();
}
Iterator<V> getDelegateIterator() {
validateIterator();
return delegateIterator;
}
}
@Override public boolean add(V value) {
refreshIfEmpty();
boolean wasEmpty = delegate.isEmpty();
boolean changed = delegate.add(value);
if (changed) {
totalSize++;
if (wasEmpty) {
addToMap();
}
}
return changed;
}
WrappedCollection getAncestor() {
return ancestor;
}
// The following methods are provided for better performance.
@Override public boolean addAll(Collection<? extends V> collection) {
if (collection.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.addAll(collection);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override public boolean contains(Object o) {
refreshIfEmpty();
return delegate.contains(o);
}
@Override public boolean containsAll(Collection<?> c) {
refreshIfEmpty();
return delegate.containsAll(c);
}
@Override public void clear() {
int oldSize = size(); // calls refreshIfEmpty
if (oldSize == 0) {
return;
}
delegate.clear();
totalSize -= oldSize;
removeIfEmpty(); // maybe shouldn't be removed if this is a sublist
}
@Override public boolean remove(Object o) {
refreshIfEmpty();
boolean changed = delegate.remove(o);
if (changed) {
totalSize--;
removeIfEmpty();
}
return changed;
}
@Override public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.removeAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
@Override public boolean retainAll(Collection<?> c) {
checkNotNull(c);
int oldSize = size(); // calls refreshIfEmpty
boolean changed = delegate.retainAll(c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
private Iterator<V> iteratorOrListIterator(Collection<V> collection) {
return (collection instanceof List)
? ((List<V>) collection).listIterator()
: collection.iterator();
}
/** Set decorator that stays in sync with the multimap values for a key. */
private class WrappedSet extends WrappedCollection implements Set<V> {
WrappedSet(@Nullable K key, Set<V> delegate) {
super(key, delegate, null);
}
@Override
public boolean removeAll(Collection<?> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
// Guava issue 1013: AbstractSet and most JDK set implementations are
// susceptible to quadratic removeAll performance on lists;
// use a slightly smarter implementation here
boolean changed = Sets.removeAllImpl((Set<V>) delegate, c);
if (changed) {
int newSize = delegate.size();
totalSize += (newSize - oldSize);
removeIfEmpty();
}
return changed;
}
}
/**
* SortedSet decorator that stays in sync with the multimap values for a key.
*/
private class WrappedSortedSet extends WrappedCollection
implements SortedSet<V> {
WrappedSortedSet(@Nullable K key, SortedSet<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
SortedSet<V> getSortedSetDelegate() {
return (SortedSet<V>) getDelegate();
}
@Override
public Comparator<? super V> comparator() {
return getSortedSetDelegate().comparator();
}
@Override
public V first() {
refreshIfEmpty();
return getSortedSetDelegate().first();
}
@Override
public V last() {
refreshIfEmpty();
return getSortedSetDelegate().last();
}
@Override
public SortedSet<V> headSet(V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().headSet(toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> subSet(V fromElement, V toElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().subSet(fromElement, toElement),
(getAncestor() == null) ? this : getAncestor());
}
@Override
public SortedSet<V> tailSet(V fromElement) {
refreshIfEmpty();
return new WrappedSortedSet(
getKey(), getSortedSetDelegate().tailSet(fromElement),
(getAncestor() == null) ? this : getAncestor());
}
}
/** List decorator that stays in sync with the multimap values for a key. */
private class WrappedList extends WrappedCollection implements List<V> {
WrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
List<V> getListDelegate() {
return (List<V>) getDelegate();
}
@Override
public boolean addAll(int index, Collection<? extends V> c) {
if (c.isEmpty()) {
return false;
}
int oldSize = size(); // calls refreshIfEmpty
boolean changed = getListDelegate().addAll(index, c);
if (changed) {
int newSize = getDelegate().size();
totalSize += (newSize - oldSize);
if (oldSize == 0) {
addToMap();
}
}
return changed;
}
@Override
public V get(int index) {
refreshIfEmpty();
return getListDelegate().get(index);
}
@Override
public V set(int index, V element) {
refreshIfEmpty();
return getListDelegate().set(index, element);
}
@Override
public void add(int index, V element) {
refreshIfEmpty();
boolean wasEmpty = getDelegate().isEmpty();
getListDelegate().add(index, element);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
@Override
public V remove(int index) {
refreshIfEmpty();
V value = getListDelegate().remove(index);
totalSize--;
removeIfEmpty();
return value;
}
@Override
public int indexOf(Object o) {
refreshIfEmpty();
return getListDelegate().indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
refreshIfEmpty();
return getListDelegate().lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
refreshIfEmpty();
return new WrappedListIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
refreshIfEmpty();
return new WrappedListIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
refreshIfEmpty();
return wrapList(getKey(),
getListDelegate().subList(fromIndex, toIndex),
(getAncestor() == null) ? this : getAncestor());
}
/** ListIterator decorator. */
private class WrappedListIterator extends WrappedIterator
implements ListIterator<V> {
WrappedListIterator() {}
public WrappedListIterator(int index) {
super(getListDelegate().listIterator(index));
}
private ListIterator<V> getDelegateListIterator() {
return (ListIterator<V>) getDelegateIterator();
}
@Override
public boolean hasPrevious() {
return getDelegateListIterator().hasPrevious();
}
@Override
public V previous() {
return getDelegateListIterator().previous();
}
@Override
public int nextIndex() {
return getDelegateListIterator().nextIndex();
}
@Override
public int previousIndex() {
return getDelegateListIterator().previousIndex();
}
@Override
public void set(V value) {
getDelegateListIterator().set(value);
}
@Override
public void add(V value) {
boolean wasEmpty = isEmpty();
getDelegateListIterator().add(value);
totalSize++;
if (wasEmpty) {
addToMap();
}
}
}
}
/**
* List decorator that stays in sync with the multimap values for a key and
* supports rapid random access.
*/
private class RandomAccessWrappedList extends WrappedList
implements RandomAccess {
RandomAccessWrappedList(@Nullable K key, List<V> delegate,
@Nullable WrappedCollection ancestor) {
super(key, delegate, ancestor);
}
}
@Override
Set<K> createKeySet() {
// TreeMultimap uses NavigableKeySet explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedKeySet((SortedMap<K, Collection<V>>) map) : new KeySet(map);
}
private class KeySet extends Maps.KeySet<K, Collection<V>> {
KeySet(final Map<K, Collection<V>> subMap) {
super(subMap);
}
@Override public Iterator<K> iterator() {
final Iterator<Map.Entry<K, Collection<V>>> entryIterator
= map().entrySet().iterator();
return new Iterator<K>() {
Map.Entry<K, Collection<V>> entry;
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public K next() {
entry = entryIterator.next();
return entry.getKey();
}
@Override
public void remove() {
Iterators.checkRemove(entry != null);
Collection<V> collection = entry.getValue();
entryIterator.remove();
totalSize -= collection.size();
collection.clear();
}
};
}
// The following methods are included for better performance.
@Override public boolean remove(Object key) {
int count = 0;
Collection<V> collection = map().remove(key);
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count > 0;
}
@Override
public void clear() {
Iterators.clear(iterator());
}
@Override public boolean containsAll(Collection<?> c) {
return map().keySet().containsAll(c);
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.map().keySet().equals(object);
}
@Override public int hashCode() {
return map().keySet().hashCode();
}
}
private class SortedKeySet extends KeySet implements SortedSet<K> {
SortedKeySet(SortedMap<K, Collection<V>> subMap) {
super(subMap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K first() {
return sortedMap().firstKey();
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet(sortedMap().headMap(toElement));
}
@Override
public K last() {
return sortedMap().lastKey();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet(sortedMap().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet(sortedMap().tailMap(fromElement));
}
}
/**
* Removes all values for the provided key. Unlike {@link #removeAll}, it
* returns the number of removed mappings.
*/
private int removeValuesForKey(Object key) {
Collection<V> collection = Maps.safeRemove(map, key);
int count = 0;
if (collection != null) {
count = collection.size();
collection.clear();
totalSize -= count;
}
return count;
}
private abstract class Itr<T> implements Iterator<T> {
final Iterator<Map.Entry<K, Collection<V>>> keyIterator;
K key;
Collection<V> collection;
Iterator<V> valueIterator;
Itr() {
keyIterator = map.entrySet().iterator();
key = null;
collection = null;
valueIterator = Iterators.emptyModifiableIterator();
}
abstract T output(K key, V value);
@Override
public boolean hasNext() {
return keyIterator.hasNext() || valueIterator.hasNext();
}
@Override
public T next() {
if (!valueIterator.hasNext()) {
Map.Entry<K, Collection<V>> mapEntry = keyIterator.next();
key = mapEntry.getKey();
collection = mapEntry.getValue();
valueIterator = collection.iterator();
}
return output(key, valueIterator.next());
}
@Override
public void remove() {
valueIterator.remove();
if (collection.isEmpty()) {
keyIterator.remove();
}
totalSize--;
}
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*/
@Override public Collection<V> values() {
return super.values();
}
@Override
Iterator<V> valueIterator() {
return new Itr<V>() {
@Override
V output(K key, V value) {
return value;
}
};
}
/*
* TODO(kevinb): should we copy this javadoc to each concrete class, so that
* classes like LinkedHashMultimap that need to say something different are
* still able to {@inheritDoc} all the way from Multimap?
*/
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* for one key, followed by the values of a second key, and so on.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override
public Collection<Map.Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns an iterator across all key-value map entries, used by {@code
* entries().iterator()} and {@code values().iterator()}. The default
* behavior, which traverses the values for one key, the values for a second
* key, and so on, suffices for most {@code AbstractMapBasedMultimap} implementations.
*
* @return an iterator across map entries
*/
@Override
Iterator<Map.Entry<K, V>> entryIterator() {
return new Itr<Map.Entry<K, V>>() {
@Override
Entry<K, V> output(K key, V value) {
return Maps.immutableEntry(key, value);
}
};
}
@Override
Map<K, Collection<V>> createAsMap() {
// TreeMultimap uses NavigableAsMap explicitly, but we don't handle that here for GWT
// compatibility reasons
return (map instanceof SortedMap)
? new SortedAsMap((SortedMap<K, Collection<V>>) map) : new AsMap(map);
}
private class AsMap extends ImprovedAbstractMap<K, Collection<V>> {
/**
* Usually the same as map, but smaller for the headMap(), tailMap(), or
* subMap() of a SortedAsMap.
*/
final transient Map<K, Collection<V>> submap;
AsMap(Map<K, Collection<V>> submap) {
this.submap = submap;
}
@Override
protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new AsMapEntries();
}
// The following methods are included for performance.
@Override public boolean containsKey(Object key) {
return Maps.safeContainsKey(submap, key);
}
@Override public Collection<V> get(Object key) {
Collection<V> collection = Maps.safeGet(submap, key);
if (collection == null) {
return null;
}
@SuppressWarnings("unchecked")
K k = (K) key;
return wrapCollection(k, collection);
}
@Override public Set<K> keySet() {
return AbstractMapBasedMultimap.this.keySet();
}
@Override
public int size() {
return submap.size();
}
@Override public Collection<V> remove(Object key) {
Collection<V> collection = submap.remove(key);
if (collection == null) {
return null;
}
Collection<V> output = createCollection();
output.addAll(collection);
totalSize -= collection.size();
collection.clear();
return output;
}
@Override public boolean equals(@Nullable Object object) {
return this == object || submap.equals(object);
}
@Override public int hashCode() {
return submap.hashCode();
}
@Override public String toString() {
return submap.toString();
}
@Override
public void clear() {
if (submap == map) {
AbstractMapBasedMultimap.this.clear();
} else {
Iterators.clear(new AsMapIterator());
}
}
Entry<K, Collection<V>> wrapEntry(Entry<K, Collection<V>> entry) {
K key = entry.getKey();
return Maps.immutableEntry(key, wrapCollection(key, entry.getValue()));
}
class AsMapEntries extends Maps.EntrySet<K, Collection<V>> {
@Override
Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
return new AsMapIterator();
}
// The following methods are included for performance.
@Override public boolean contains(Object o) {
return Collections2.safeContains(submap.entrySet(), o);
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
/** Iterator across all keys and value collections. */
class AsMapIterator implements Iterator<Map.Entry<K, Collection<V>>> {
final Iterator<Map.Entry<K, Collection<V>>> delegateIterator
= submap.entrySet().iterator();
Collection<V> collection;
@Override
public boolean hasNext() {
return delegateIterator.hasNext();
}
@Override
public Map.Entry<K, Collection<V>> next() {
Map.Entry<K, Collection<V>> entry = delegateIterator.next();
collection = entry.getValue();
return wrapEntry(entry);
}
@Override
public void remove() {
delegateIterator.remove();
totalSize -= collection.size();
collection.clear();
}
}
}
private class SortedAsMap extends AsMap
implements SortedMap<K, Collection<V>> {
SortedAsMap(SortedMap<K, Collection<V>> submap) {
super(submap);
}
SortedMap<K, Collection<V>> sortedMap() {
return (SortedMap<K, Collection<V>>) submap;
}
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public K firstKey() {
return sortedMap().firstKey();
}
@Override
public K lastKey() {
return sortedMap().lastKey();
}
@Override
public SortedMap<K, Collection<V>> headMap(K toKey) {
return new SortedAsMap(sortedMap().headMap(toKey));
}
@Override
public SortedMap<K, Collection<V>> subMap(K fromKey, K toKey) {
return new SortedAsMap(sortedMap().subMap(fromKey, toKey));
}
@Override
public SortedMap<K, Collection<V>> tailMap(K fromKey) {
return new SortedAsMap(sortedMap().tailMap(fromKey));
}
SortedSet<K> sortedKeySet;
// returns a SortedSet, even though returning a Set would be sufficient to
// satisfy the SortedMap.keySet() interface
@Override public SortedSet<K> keySet() {
SortedSet<K> result = sortedKeySet;
return (result == null) ? sortedKeySet = createKeySet() : result;
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet(sortedMap());
}
}
private static final long serialVersionUID = 2447537837011683357L;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link List} instances. Also see this
* class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
* {@code Lists}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Lists {
private Lists() {}
// ArrayList
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableList#of()} instead.
*
* @return a new, empty {@code ArrayList}
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableList#of()} (for varargs) or
* {@link ImmutableList#copyOf(Object[])} (for an array) instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements); // for GWT
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@VisibleForTesting static int computeArrayListCapacity(int arraySize) {
checkArgument(arraySize >= 0);
// TODO(kevinb): Figure out the right behavior, and document it
return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code ArrayList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
/**
* Creates an {@code ArrayList} instance backed by an array of the
* <i>exact</i> size specified; equivalent to
* {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note:</b> if you know the exact size your list will be, consider
* using a fixed-size list ({@link Arrays#asList(Object[])}) or an {@link
* ImmutableList} instead of a growable {@link ArrayList}.
*
* <p><b>Note:</b> If you have only an <i>estimate</i> of the eventual size of
* the list, consider padding this estimate by a suitable amount, or simply
* use {@link #newArrayListWithExpectedSize(int)} instead.
*
* @param initialArraySize the exact size of the initial backing array for
* the returned array list ({@code ArrayList} documentation calls this
* value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize
* itself unless its size reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithCapacity(
int initialArraySize) {
checkArgument(initialArraySize >= 0); // for GWT.
return new ArrayList<E>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance sized appropriately to hold an
* <i>estimated</i> number of elements without resizing. A small amount of
* padding is added in case the estimate is low.
*
* <p><b>Note:</b> If you know the <i>exact</i> number of elements the list
* will hold, or prefer to calculate your own amount of padding, refer to
* {@link #newArrayListWithCapacity(int)}.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of
* the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the
* estimated number of elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(
int estimatedSize) {
return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
}
// LinkedList
/**
* Creates an empty {@code LinkedList} instance.
*
* <p><b>Note:</b> if you need an immutable empty {@link List}, use
* {@link ImmutableList#of()} instead.
*
* @return a new, empty {@code LinkedList}
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList() {
return new LinkedList<E>();
}
/**
* Creates a {@code LinkedList} instance containing the given elements.
*
* @param elements the elements that the list should contain, in order
* @return a new {@code LinkedList} containing those elements
*/
@GwtCompatible(serializable = true)
public static <E> LinkedList<E> newLinkedList(
Iterable<? extends E> elements) {
LinkedList<E> list = newLinkedList();
Iterables.addAll(list, elements);
return list;
}
/**
* Returns an unmodifiable list containing the specified first element and
* backed by the specified array of additional elements. Changes to the {@code
* rest} array will be reflected in the returned list. Unlike {@link
* Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
* ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(@Nullable E first, E[] rest) {
return new OnePlusArrayList<E>(first, rest);
}
/** @see Lists#asList(Object, Object[]) */
private static class OnePlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E[] rest;
OnePlusArrayList(@Nullable E first, E[] rest) {
this.first = first;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 1;
}
@Override public E get(int index) {
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return (index == 0) ? first : rest[index - 1];
}
private static final long serialVersionUID = 0;
}
/**
* Returns an unmodifiable list containing the specified first and second
* element, and backed by the specified array of additional elements. Changes
* to the {@code rest} array will be reflected in the returned list. Unlike
* {@link Arrays#asList}, the returned list is unmodifiable.
*
* <p>This is useful when a varargs method needs to use a signature such as
* {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
* overload ambiguity or to enforce a minimum argument count.
*
* <p>The returned list is serializable and implements {@link RandomAccess}.
*
* @param first the first element
* @param second the second element
* @param rest an array of additional elements, possibly empty
* @return an unmodifiable list containing the specified elements
*/
public static <E> List<E> asList(
@Nullable E first, @Nullable E second, E[] rest) {
return new TwoPlusArrayList<E>(first, second, rest);
}
/** @see Lists#asList(Object, Object, Object[]) */
private static class TwoPlusArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess {
final E first;
final E second;
final E[] rest;
TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
this.first = first;
this.second = second;
this.rest = checkNotNull(rest);
}
@Override public int size() {
return rest.length + 2;
}
@Override public E get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
// check explicitly so the IOOBE will have the right message
checkElementIndex(index, size());
return rest[index - 2];
}
}
private static final long serialVersionUID = 0;
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the {@code lists},
* or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends List<? extends B>> lists) {
return CartesianList.create(lists);
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given lists in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the lists. For example: <pre> {@code
*
* Lists.cartesianProduct(ImmutableList.of(
* ImmutableList.of(1, 2),
* ImmutableList.of("A", "B", "C")))}</pre>
*
* <p>returns a list containing six lists in the following order:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : lists.get(0)) {
* for (B b1 : lists.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input list is empty, the Cartesian product will also be
* empty. If no lists at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of lists of size
* {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian product is constructed, the
* input lists are merely copied. Only as the resulting list is iterated are
* the individual lists created, and these are not retained after iteration.
*
* @param lists the lists to choose elements from, in the order that
* the elements chosen from those lists should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable list containing immutable
* lists
* @throws IllegalArgumentException if the size of the cartesian product would
* be greater than {@link Integer#MAX_VALUE}
* @throws NullPointerException if {@code lists}, any one of the
* {@code lists}, or any element of a provided list is null
*/ static <B> List<List<B>>
cartesianProduct(List<? extends B>... lists) {
return cartesianProduct(Arrays.asList(lists));
}
/**
* Returns a list that applies {@code function} to each element of {@code
* fromList}. The returned list is a transformed view of {@code fromList};
* changes to {@code fromList} will be reflected in the returned list and vice
* versa.
*
* <p>Since functions are not reversible, the transform is one-way and new
* items cannot be stored in the returned list. The {@code add},
* {@code addAll} and {@code set} methods are unsupported in the returned
* list.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned list to be a view, but it means that the function will be
* applied many times for bulk operations like {@link List#contains} and
* {@link List#hashCode}. For this to perform well, {@code function} should be
* fast. To avoid lazy evaluation when the returned list doesn't need to be a
* view, copy the returned list into a new list of your choosing.
*
* <p>If {@code fromList} implements {@link RandomAccess}, so will the
* returned list. The returned list is threadsafe if the supplied list and
* function are.
*
* <p>If only a {@code Collection} or {@code Iterable} input is available, use
* {@link Collections2#transform} or {@link Iterables#transform}.
*
* <p><b>Note:</b> serializing the returned list is implemented by serializing
* {@code fromList}, its contents, and {@code function} -- <i>not</i> by
* serializing the transformed values. This can lead to surprising behavior,
* so serializing the returned list is <b>not recommended</b>. Instead,
* copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
* then serialize the copy. Other methods similar to this do not implement
* serialization at all for this reason.
*/
public static <F, T> List<T> transform(
List<F> fromList, Function<? super F, ? extends T> function) {
return (fromList instanceof RandomAccess)
? new TransformingRandomAccessList<F, T>(fromList, function)
: new TransformingSequentialList<F, T>(fromList, function);
}
/**
* Implementation of a sequential transforming list.
*
* @see Lists#transform
*/
private static class TransformingSequentialList<F, T>
extends AbstractSequentialList<T> implements Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingSequentialList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
/**
* The default implementation inherited is based on iteration and removal of
* each element which can be overkill. That's why we forward this call
* directly to the backing list.
*/
@Override public void clear() {
fromList.clear();
}
@Override public int size() {
return fromList.size();
}
@Override public ListIterator<T> listIterator(final int index) {
return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
private static final long serialVersionUID = 0;
}
/**
* Implementation of a transforming random access list. We try to make as many
* of these methods pass-through to the source list as possible so that the
* performance characteristics of the source list and transformed list are
* similar.
*
* @see Lists#transform
*/
private static class TransformingRandomAccessList<F, T>
extends AbstractList<T> implements RandomAccess, Serializable {
final List<F> fromList;
final Function<? super F, ? extends T> function;
TransformingRandomAccessList(
List<F> fromList, Function<? super F, ? extends T> function) {
this.fromList = checkNotNull(fromList);
this.function = checkNotNull(function);
}
@Override public void clear() {
fromList.clear();
}
@Override public T get(int index) {
return function.apply(fromList.get(index));
}
@Override public boolean isEmpty() {
return fromList.isEmpty();
}
@Override public T remove(int index) {
return function.apply(fromList.remove(index));
}
@Override public int size() {
return fromList.size();
}
private static final long serialVersionUID = 0;
}
/**
* Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
* each of the same size (the final list may be smaller). For example,
* partitioning a list containing {@code [a, b, c, d, e]} with a partition
* size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
* two inner lists of three and two elements, all in the original order.
*
* <p>The outer list is unmodifiable, but reflects the latest state of the
* source list. The inner lists are sublist views of the original list,
* produced on demand using {@link List#subList(int, int)}, and are subject
* to all the usual caveats about modification as explained in that API.
*
* @param list the list to return consecutive sublists of
* @param size the desired size of each sublist (the last may be
* smaller)
* @return a list of consecutive sublists
* @throws IllegalArgumentException if {@code partitionSize} is nonpositive
*/
public static <T> List<List<T>> partition(List<T> list, int size) {
checkNotNull(list);
checkArgument(size > 0);
return (list instanceof RandomAccess)
? new RandomAccessPartition<T>(list, size)
: new Partition<T>(list, size);
}
private static class Partition<T> extends AbstractList<List<T>> {
final List<T> list;
final int size;
Partition(List<T> list, int size) {
this.list = list;
this.size = size;
}
@Override public List<T> get(int index) {
checkElementIndex(index, size());
int start = index * size;
int end = Math.min(start + size, list.size());
return list.subList(start, end);
}
@Override public int size() {
return IntMath.divide(list.size(), size, RoundingMode.CEILING);
}
@Override public boolean isEmpty() {
return list.isEmpty();
}
}
private static class RandomAccessPartition<T> extends Partition<T>
implements RandomAccess {
RandomAccessPartition(List<T> list, int size) {
super(list, size);
}
}
/**
* Returns a view of the specified string as an immutable list of {@code
* Character} values.
*
* @since 7.0
*/
@Beta public static ImmutableList<Character> charactersOf(String string) {
return new StringAsImmutableList(checkNotNull(string));
}
@SuppressWarnings("serial") // serialized using ImmutableList serialization
private static final class StringAsImmutableList
extends ImmutableList<Character> {
private final String string;
StringAsImmutableList(String string) {
this.string = string;
}
@Override public int indexOf(@Nullable Object object) {
return (object instanceof Character)
? string.indexOf((Character) object) : -1;
}
@Override public int lastIndexOf(@Nullable Object object) {
return (object instanceof Character)
? string.lastIndexOf((Character) object) : -1;
}
@Override public ImmutableList<Character> subList(
int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
return charactersOf(string.substring(fromIndex, toIndex));
}
@Override boolean isPartialView() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return string.charAt(index);
}
@Override public int size() {
return string.length();
}
}
/**
* Returns a view of the specified {@code CharSequence} as a {@code
* List<Character>}, viewing {@code sequence} as a sequence of Unicode code
* units. The view does not support any modification operations, but reflects
* any changes to the underlying character sequence.
*
* @param sequence the character sequence to view as a {@code List} of
* characters
* @return an {@code List<Character>} view of the character sequence
* @since 7.0
*/
@Beta public static List<Character> charactersOf(CharSequence sequence) {
return new CharSequenceAsList(checkNotNull(sequence));
}
private static final class CharSequenceAsList
extends AbstractList<Character> {
private final CharSequence sequence;
CharSequenceAsList(CharSequence sequence) {
this.sequence = sequence;
}
@Override public Character get(int index) {
checkElementIndex(index, size()); // for GWT
return sequence.charAt(index);
}
@Override public int size() {
return sequence.length();
}
}
/**
* Returns a reversed view of the specified list. For example, {@code
* Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
* 2, 1}. The returned list is backed by this list, so changes in the returned
* list are reflected in this list, and vice-versa. The returned list supports
* all of the optional list operations supported by this list.
*
* <p>The returned list is random-access if the specified list is random
* access.
*
* @since 7.0
*/
public static <T> List<T> reverse(List<T> list) {
if (list instanceof ImmutableList) {
return ((ImmutableList<T>) list).reverse();
} else if (list instanceof ReverseList) {
return ((ReverseList<T>) list).getForwardList();
} else if (list instanceof RandomAccess) {
return new RandomAccessReverseList<T>(list);
} else {
return new ReverseList<T>(list);
}
}
private static class ReverseList<T> extends AbstractList<T> {
private final List<T> forwardList;
ReverseList(List<T> forwardList) {
this.forwardList = checkNotNull(forwardList);
}
List<T> getForwardList() {
return forwardList;
}
private int reverseIndex(int index) {
int size = size();
checkElementIndex(index, size);
return (size - 1) - index;
}
private int reversePosition(int index) {
int size = size();
checkPositionIndex(index, size);
return size - index;
}
@Override public void add(int index, @Nullable T element) {
forwardList.add(reversePosition(index), element);
}
@Override public void clear() {
forwardList.clear();
}
@Override public T remove(int index) {
return forwardList.remove(reverseIndex(index));
}
@Override protected void removeRange(int fromIndex, int toIndex) {
subList(fromIndex, toIndex).clear();
}
@Override public T set(int index, @Nullable T element) {
return forwardList.set(reverseIndex(index), element);
}
@Override public T get(int index) {
return forwardList.get(reverseIndex(index));
}
@Override public int size() {
return forwardList.size();
}
@Override public List<T> subList(int fromIndex, int toIndex) {
checkPositionIndexes(fromIndex, toIndex, size());
return reverse(forwardList.subList(
reversePosition(toIndex), reversePosition(fromIndex)));
}
@Override public Iterator<T> iterator() {
return listIterator();
}
@Override public ListIterator<T> listIterator(int index) {
int start = reversePosition(index);
final ListIterator<T> forwardIterator = forwardList.listIterator(start);
return new ListIterator<T>() {
boolean canRemoveOrSet;
@Override public void add(T e) {
forwardIterator.add(e);
forwardIterator.previous();
canRemoveOrSet = false;
}
@Override public boolean hasNext() {
return forwardIterator.hasPrevious();
}
@Override public boolean hasPrevious() {
return forwardIterator.hasNext();
}
@Override public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.previous();
}
@Override public int nextIndex() {
return reversePosition(forwardIterator.nextIndex());
}
@Override public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
canRemoveOrSet = true;
return forwardIterator.next();
}
@Override public int previousIndex() {
return nextIndex() - 1;
}
@Override public void remove() {
Iterators.checkRemove(canRemoveOrSet);
forwardIterator.remove();
canRemoveOrSet = false;
}
@Override public void set(T e) {
checkState(canRemoveOrSet);
forwardIterator.set(e);
}
};
}
}
private static class RandomAccessReverseList<T> extends ReverseList<T>
implements RandomAccess {
RandomAccessReverseList(List<T> forwardList) {
super(forwardList);
}
}
/**
* An implementation of {@link List#hashCode()}.
*/
static int hashCodeImpl(List<?> list) {
// TODO(user): worth optimizing for RandomAccess?
int hashCode = 1;
for (Object o : list) {
hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
hashCode = ~~hashCode;
// needed to deal with GWT integer overflow
}
return hashCode;
}
/**
* An implementation of {@link List#equals(Object)}.
*/
static boolean equalsImpl(List<?> list, @Nullable Object object) {
if (object == checkNotNull(list)) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> o = (List<?>) object;
return list.size() == o.size()
&& Iterators.elementsEqual(list.iterator(), o.iterator());
}
/**
* An implementation of {@link List#addAll(int, Collection)}.
*/
static <E> boolean addAllImpl(
List<E> list, int index, Iterable<? extends E> elements) {
boolean changed = false;
ListIterator<E> listIterator = list.listIterator(index);
for (E e : elements) {
listIterator.add(e);
changed = true;
}
return changed;
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
/**
* Returns an implementation of {@link List#listIterator(int)}.
*/
static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
return new AbstractListWrapper<E>(list).listIterator(index);
}
/**
* An implementation of {@link List#subList(int, int)}.
*/
static <E> List<E> subListImpl(
final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper = new RandomAccessListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
} else {
wrapper = new AbstractListWrapper<E>(list) {
@Override public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
private static class AbstractListWrapper<E> extends AbstractList<E> {
final List<E> backingList;
AbstractListWrapper(List<E> backingList) {
this.backingList = checkNotNull(backingList);
}
@Override public void add(int index, E element) {
backingList.add(index, element);
}
@Override public boolean addAll(int index, Collection<? extends E> c) {
return backingList.addAll(index, c);
}
@Override public E get(int index) {
return backingList.get(index);
}
@Override public E remove(int index) {
return backingList.remove(index);
}
@Override public E set(int index, E element) {
return backingList.set(index, element);
}
@Override public boolean contains(Object o) {
return backingList.contains(o);
}
@Override public int size() {
return backingList.size();
}
}
private static class RandomAccessListWrapper<E>
extends AbstractListWrapper<E> implements RandomAccess {
RandomAccessListWrapper(List<E> backingList) {
super(backingList);
}
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> List<T> cast(Iterable<T> iterable) {
return (List<T>) iterable;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import java.util.EnumMap;
import java.util.Iterator;
/**
* Multiset implementation backed by an {@link EnumMap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> {
/** Creates an empty {@code EnumMultiset}. */
public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) {
return new EnumMultiset<E>(type);
}
/**
* Creates a new {@code EnumMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link
* Multiset}.
*
* @param elements the elements that the multiset should contain
* @throws IllegalArgumentException if {@code elements} is empty
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) {
Iterator<E> iterator = elements.iterator();
checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable");
EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass());
Iterables.addAll(multiset, elements);
return multiset;
}
/**
* Returns a new {@code EnumMultiset} instance containing the given elements. Unlike
* {@link EnumMultiset#create(Iterable)}, this method does not produce an exception on an empty
* iterable.
*
* @since 14.0
*/
public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements, Class<E> type) {
EnumMultiset<E> result = create(type);
Iterables.addAll(result, elements);
return result;
}
private transient Class<E> type;
/** Creates an empty {@code EnumMultiset}. */
private EnumMultiset(Class<E> type) {
super(WellBehavedMap.wrap(new EnumMap<E, Count>(type)));
this.type = type;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code values()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
final class ImmutableMapValues<K, V> extends ImmutableCollection<V> {
private final ImmutableMap<K, V> map;
ImmutableMapValues(ImmutableMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<V> iterator() {
return Maps.valueIterator(map.entrySet().iterator());
}
@Override
public boolean contains(@Nullable Object object) {
return object != null && Iterators.contains(iterator(), object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
ImmutableList<V> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList();
return new ImmutableAsList<V>() {
@Override
public V get(int index) {
return entryList.get(index).getValue();
}
@Override
ImmutableCollection<V> delegateCollection() {
return ImmutableMapValues.this;
}
};
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* {@code FluentIterable} provides a rich interface for manipulating {@code Iterable} instances in a
* chained fashion. A {@code FluentIterable} can be created from an {@code Iterable}, or from a set
* of elements. The following types of methods are provided on {@code FluentIterable}:
* <ul>
* <li>chained methods which return a new {@code FluentIterable} based in some way on the contents
* of the current one (for example {@link #transform})
* <li>conversion methods which copy the {@code FluentIterable}'s contents into a new collection or
* array (for example {@link #toList})
* <li>element extraction methods which facilitate the retrieval of certain elements (for example
* {@link #last})
* <li>query methods which answer questions about the {@code FluentIterable}'s contents (for example
* {@link #anyMatch})
* </ul>
*
* <p>Here is an example that merges the lists returned by two separate database calls, transforms
* it by invoking {@code toString()} on each element, and returns the first 10 elements as an
* {@code ImmutableList}: <pre> {@code
*
* FluentIterable
* .from(database.getClientList())
* .filter(activeInLastMonth())
* .transform(Functions.toStringFunction())
* .limit(10)
* .toList();}</pre>
*
* <p>Anything which can be done using {@code FluentIterable} could be done in a different fashion
* (often with {@link Iterables}), however the use of {@code FluentIterable} makes many sets of
* operations significantly more concise.
*
* @author Marcin Mikosik
* @since 12.0
*/
@GwtCompatible(emulated = true)
public abstract class FluentIterable<E> implements Iterable<E> {
// We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
// checks on the _original_ iterable when FluentIterable.from is used.
private final Iterable<E> iterable;
/** Constructor for use by subclasses. */
protected FluentIterable() {
this.iterable = this;
}
FluentIterable(Iterable<E> iterable) {
this.iterable = checkNotNull(iterable);
}
/**
* Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it
* is already a {@code FluentIterable}.
*/
public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
return (iterable instanceof FluentIterable) ? (FluentIterable<E>) iterable
: new FluentIterable<E>(iterable) {
@Override
public Iterator<E> iterator() {
return iterable.iterator();
}
};
}
/**
* Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
* but is intended to help call out cases where one migration from {@code Iterable} to
* {@code FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
*
* @deprecated instances of {@code FluentIterable} don't need to be converted to
* {@code FluentIterable}
*/
@Deprecated
public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
return checkNotNull(iterable);
}
/**
* Returns a string representation of this fluent iterable, with the format
* {@code [e1, e2, ..., en]}.
*/
@Override
public String toString() {
return Iterables.toString(iterable);
}
/**
* Returns the number of elements in this fluent iterable.
*/
public final int size() {
return Iterables.size(iterable);
}
/**
* Returns {@code true} if this fluent iterable contains any object for which
* {@code equals(element)} is true.
*/
public final boolean contains(@Nullable Object element) {
return Iterables.contains(iterable, element);
}
/**
* Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of
* this fluent iterable.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After
* {@code remove()} is called, subsequent cycles omit the removed element, which is no longer in
* this fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until
* this fluent iterable is empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You
* should use an explicit {@code break} or be certain that you will eventually remove all the
* elements.
*/
@CheckReturnValue
public final FluentIterable<E> cycle() {
return from(Iterables.cycle(iterable));
}
/**
* Returns the elements from this fluent iterable that satisfy a predicate. The
* resulting fluent iterable's iterator does not support {@code remove()}.
*/
@CheckReturnValue
public final FluentIterable<E> filter(Predicate<? super E> predicate) {
return from(Iterables.filter(iterable, predicate));
}
/**
* Returns {@code true} if any element in this fluent iterable satisfies the predicate.
*/
public final boolean anyMatch(Predicate<? super E> predicate) {
return Iterables.any(iterable, predicate);
}
/**
* Returns {@code true} if every element in this fluent iterable satisfies the predicate.
* If this fluent iterable is empty, {@code true} is returned.
*/
public final boolean allMatch(Predicate<? super E> predicate) {
return Iterables.all(iterable, predicate);
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable that
* satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
* is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
*/
public final Optional<E> firstMatch(Predicate<? super E> predicate) {
return Iterables.tryFind(iterable, predicate);
}
/**
* Returns a fluent iterable that applies {@code function} to each element of this
* fluent iterable.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this iterable's
* iterator does. After a successful {@code remove()} call, this fluent iterable no longer
* contains the corresponding element.
*/
public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
return from(Iterables.transform(iterable, function));
}
/**
* Applies {@code function} to each element of this fluent iterable and returns
* a fluent iterable with the concatenated combination of results. {@code function}
* returns an Iterable of results.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if this
* function-returned iterables' iterator does. After a successful {@code remove()} call,
* the returned fluent iterable no longer contains the corresponding element.
*
* @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
*/
public <T> FluentIterable<T> transformAndConcat(
Function<? super E, ? extends Iterable<? extends T>> function) {
return from(Iterables.concat(transform(function)));
}
/**
* Returns an {@link Optional} containing the first element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the first element is null; if this is a possibility, use
* {@code iterator().next()} or {@link Iterables#getFirst} instead.
*/
public final Optional<E> first() {
Iterator<E> iterator = iterable.iterator();
return iterator.hasNext()
? Optional.of(iterator.next())
: Optional.<E>absent();
}
/**
* Returns an {@link Optional} containing the last element in this fluent iterable.
* If the iterable is empty, {@code Optional.absent()} is returned.
*
* @throws NullPointerException if the last element is null; if this is a possibility, use
* {@link Iterables#getLast} instead.
*/
public final Optional<E> last() {
// Iterables#getLast was inlined here so we don't have to throw/catch a NSEE
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<E> list = (List<E>) iterable;
if (list.isEmpty()) {
return Optional.absent();
}
return Optional.of(list.get(list.size() - 1));
}
Iterator<E> iterator = iterable.iterator();
if (!iterator.hasNext()) {
return Optional.absent();
}
/*
* TODO(kevinb): consider whether this "optimization" is worthwhile. Users
* with SortedSets tend to know they are SortedSets and probably would not
* call this method.
*/
if (iterable instanceof SortedSet) {
SortedSet<E> sortedSet = (SortedSet<E>) iterable;
return Optional.of(sortedSet.last());
}
while (true) {
E current = iterator.next();
if (!iterator.hasNext()) {
return Optional.of(current);
}
}
}
/**
* Returns a view of this fluent iterable that skips its first {@code numberToSkip}
* elements. If this fluent iterable contains fewer than {@code numberToSkip} elements,
* the returned fluent iterable skips all of its elements.
*
* <p>Modifications to this fluent iterable before a call to {@code iterator()} are
* reflected in the returned fluent iterable. That is, the its iterator skips the first
* {@code numberToSkip} elements that exist when the iterator is created, not when {@code skip()}
* is called.
*
* <p>The returned fluent iterable's iterator supports {@code remove()} if the
* {@code Iterator} of this fluent iterable supports it. Note that it is <i>not</i>
* possible to delete the last skipped element by immediately calling {@code remove()} on the
* returned fluent iterable's iterator, as the {@code Iterator} contract states that a call
* to {@code * remove()} before a call to {@code next()} will throw an
* {@link IllegalStateException}.
*/
@CheckReturnValue
public final FluentIterable<E> skip(int numberToSkip) {
return from(Iterables.skip(iterable, numberToSkip));
}
/**
* Creates a fluent iterable with the first {@code size} elements of this
* fluent iterable. If this fluent iterable does not contain that many elements,
* the returned fluent iterable will have the same behavior as this fluent iterable.
* The returned fluent iterable's iterator supports {@code remove()} if this
* fluent iterable's iterator does.
*
* @param size the maximum number of elements in the returned fluent iterable
* @throws IllegalArgumentException if {@code size} is negative
*/
@CheckReturnValue
public final FluentIterable<E> limit(int size) {
return from(Iterables.limit(iterable, size));
}
/**
* Determines whether this fluent iterable is empty.
*/
public final boolean isEmpty() {
return !iterable.iterator().hasNext();
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
* proper sequence.
*
* @since 14.0 (since 12.0 as {@code toImmutableList()}).
*/
public final ImmutableList<E> toList() {
return ImmutableList.copyOf(iterable);
}
/**
* Returns an {@code ImmutableList} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}. To produce an {@code
* ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
*
* @param comparator the function by which to sort list elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
*/
@Beta
public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
return Ordering.from(comparator).immutableSortedCopy(iterable);
}
/**
* Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
* duplicates removed.
*
* @since 14.0 (since 12.0 as {@code toImmutableSet()}).
*/
public final ImmutableSet<E> toSet() {
return ImmutableSet.copyOf(iterable);
}
/**
* Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
* FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
* {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
* by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
*
* @param comparator the function by which to sort set elements
* @throws NullPointerException if any element is null
* @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
*/
public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
return ImmutableSortedSet.copyOf(comparator, iterable);
}
/**
* Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in
* the same order, mapped to values by the given function. If this iterable contains duplicate
* elements, the returned map will contain each distinct element once in the order it first
* appears.
*
* @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
return Maps.toMap(iterable, valueFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of applying a
* specified function to each item in this {@code FluentIterable} of values. Each element of this
* iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
* size as this iterable. The key used to store that value in the multimap will be the result of
* calling the function on that value. The resulting multimap is created as an immutable snapshot.
* In the returned multimap, keys appear in the order they are first encountered, and the values
* corresponding to each key appear in the same order as they are encountered.
*
* @param keyFunction the function used to produce the key for each value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code keyFunction} is null
* <li>An element in this fluent iterable is null
* <li>{@code keyFunction} returns {@code null} for any element of this iterable
* </ul>
* @since 14.0
*/
public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
return Multimaps.index(iterable, keyFunction);
}
/**
* Returns an immutable map for which the {@link java.util.Map#values} are the elements of this
* {@code FluentIterable} in the given order, and each key is the product of invoking a supplied
* function on its corresponding value.
*
* @param keyFunction the function used to produce the key for each value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in this fluent iterable
* @throws NullPointerException if any element of this fluent iterable is null, or if
* {@code keyFunction} produces {@code null} for any value
* @since 14.0
*/
public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
return Maps.uniqueIndex(iterable, keyFunction);
}
/**
* Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
* calling {@code Iterables.addAll(collection, this)}.
*
* @param collection the collection to copy elements to
* @return {@code collection}, for convenience
* @since 14.0
*/
public final <C extends Collection<? super E>> C copyInto(C collection) {
checkNotNull(collection);
if (iterable instanceof Collection) {
collection.addAll(Collections2.cast(iterable));
} else {
for (E item : iterable) {
collection.add(item);
}
}
return collection;
}
/**
* Returns the element at the specified position in this fluent iterable.
*
* @param position position of the element to return
* @return the element at the specified position in this fluent iterable
* @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
* the size of this fluent iterable
*/
public final E get(int position) {
return Iterables.get(iterable, position);
}
/**
* Function that transforms {@code Iterable<E>} into a fluent iterable.
*/
private static class FromIterableFunction<E>
implements Function<Iterable<E>, FluentIterable<E>> {
@Override
public FluentIterable<E> apply(Iterable<E> fromObject) {
return FluentIterable.from(fromObject);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code keySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
final class ImmutableMapKeySet<K, V> extends ImmutableSet<K> {
private final ImmutableMap<K, V> map;
ImmutableMapKeySet(ImmutableMap<K, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public UnmodifiableIterator<K> iterator() {
return asList().iterator();
}
@Override
public boolean contains(@Nullable Object object) {
return map.containsKey(object);
}
@Override
ImmutableList<K> createAsList() {
final ImmutableList<Entry<K, V>> entryList = map.entrySet().asList();
return new ImmutableAsList<K>() {
@Override
public K get(int index) {
return entryList.get(index).getKey();
}
@Override
ImmutableCollection<K> delegateCollection() {
return ImmutableMapKeySet.this;
}
};
}
@Override
boolean isPartialView() {
return true;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
/**
* List returned by {@code ImmutableSortedSet.asList()} when the set isn't empty.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial")
final class ImmutableSortedAsList<E> extends RegularImmutableAsList<E>
implements SortedIterable<E> {
ImmutableSortedAsList(
ImmutableSortedSet<E> backingSet, ImmutableList<E> backingList) {
super(backingSet, backingList);
}
@Override
ImmutableSortedSet<E> delegateCollection() {
return (ImmutableSortedSet<E>) super.delegateCollection();
}
@Override public Comparator<? super E> comparator() {
return delegateCollection().comparator();
}
// Override indexOf() and lastIndexOf() to be O(log N) instead of O(N).
@Override
public boolean contains(Object target) {
// Necessary for ISS's with comparators inconsistent with equals.
return indexOf(target) >= 0;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.BoundType.CLOSED;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* An implementation of {@link ContiguousSet} that contains one or more elements.
*
* @author Gregory Kick
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> {
private final Range<C> range;
RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) {
super(domain);
this.range = range;
}
private ContiguousSet<C> intersectionInCurrentDomain(Range<C> other) {
return (range.isConnected(other))
? ContiguousSet.create(range.intersection(other), domain)
: new EmptyContiguousSet<C>(domain);
}
@Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive)));
}
@Override ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement,
boolean toInclusive) {
if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) {
// Range would reject our attempt to create (x, x).
return new EmptyContiguousSet<C>(domain);
}
return intersectionInCurrentDomain(Range.range(
fromElement, BoundType.forBoolean(fromInclusive),
toElement, BoundType.forBoolean(toInclusive)));
}
@Override ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) {
return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive)));
}
@Override public UnmodifiableIterator<C> iterator() {
return new AbstractSequentialIterator<C>(first()) {
final C last = last();
@Override
protected C computeNext(C previous) {
return equalsOrThrow(previous, last) ? null : domain.next(previous);
}
};
}
private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) {
return right != null && Range.compareOrThrow(left, right) == 0;
}
@Override boolean isPartialView() {
return false;
}
@Override public C first() {
return range.lowerBound.leastValueAbove(domain);
}
@Override public C last() {
return range.upperBound.greatestValueBelow(domain);
}
@Override public int size() {
long distance = domain.distance(first(), last());
return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1;
}
@Override public boolean contains(@Nullable Object object) {
if (object == null) {
return false;
}
try {
return range.contains((C) object);
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsAll(Collection<?> targets) {
return Collections2.containsAllImpl(this, targets);
}
@Override public boolean isEmpty() {
return false;
}
@Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
checkNotNull(other);
checkArgument(this.domain.equals(other.domain));
if (other.isEmpty()) {
return other;
} else {
C lowerEndpoint = Ordering.natural().max(this.first(), other.first());
C upperEndpoint = Ordering.natural().min(this.last(), other.last());
return (lowerEndpoint.compareTo(upperEndpoint) < 0)
? ContiguousSet.create(Range.closed(lowerEndpoint, upperEndpoint), domain)
: new EmptyContiguousSet<C>(domain);
}
}
@Override public Range<C> range() {
return range(CLOSED, CLOSED);
}
@Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
return Range.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain),
range.upperBound.withUpperBoundType(upperBoundType, domain));
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
} else if (object instanceof RegularContiguousSet) {
RegularContiguousSet<?> that = (RegularContiguousSet<?>) object;
if (this.domain.equals(that.domain)) {
return this.first().equals(that.first())
&& this.last().equals(that.last());
}
}
return super.equals(object);
}
// copied to make sure not to use the GWT-emulated version
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A general-purpose bimap implementation using any two backing {@code Map}
* instances.
*
* <p>Note that this class contains {@code equals()} calls that keep it from
* supporting {@code IdentityHashMap} backing maps.
*
* @author Kevin Bourrillion
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V>
implements BiMap<K, V>, Serializable {
private transient Map<K, V> delegate;
transient AbstractBiMap<V, K> inverse;
/** Package-private constructor for creating a map-backed bimap. */
AbstractBiMap(Map<K, V> forward, Map<V, K> backward) {
setDelegates(forward, backward);
}
/** Private constructor for inverse bimap. */
private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) {
delegate = backward;
inverse = forward;
}
@Override protected Map<K, V> delegate() {
return delegate;
}
/**
* Returns its input, or throws an exception if this is not a valid key.
*/
K checkKey(@Nullable K key) {
return key;
}
/**
* Returns its input, or throws an exception if this is not a valid value.
*/
V checkValue(@Nullable V value) {
return value;
}
/**
* Specifies the delegate maps going in each direction. Called by the
* constructor and by subclasses during deserialization.
*/
void setDelegates(Map<K, V> forward, Map<V, K> backward) {
checkState(delegate == null);
checkState(inverse == null);
checkArgument(forward.isEmpty());
checkArgument(backward.isEmpty());
checkArgument(forward != backward);
delegate = forward;
inverse = new Inverse<V, K>(backward, this);
}
void setInverse(AbstractBiMap<V, K> inverse) {
this.inverse = inverse;
}
// Query Operations (optimizations)
@Override public boolean containsValue(@Nullable Object value) {
return inverse.containsKey(value);
}
// Modification Operations
@Override public V put(@Nullable K key, @Nullable V value) {
return putInBothMaps(key, value, false);
}
@Override
public V forcePut(@Nullable K key, @Nullable V value) {
return putInBothMaps(key, value, true);
}
private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) {
checkKey(key);
checkValue(value);
boolean containedKey = containsKey(key);
if (containedKey && Objects.equal(value, get(key))) {
return value;
}
if (force) {
inverse().remove(value);
} else {
checkArgument(!containsValue(value), "value already present: %s", value);
}
V oldValue = delegate.put(key, value);
updateInverseMap(key, containedKey, oldValue, value);
return oldValue;
}
private void updateInverseMap(
K key, boolean containedKey, V oldValue, V newValue) {
if (containedKey) {
removeFromInverseMap(oldValue);
}
inverse.delegate.put(newValue, key);
}
@Override public V remove(@Nullable Object key) {
return containsKey(key) ? removeFromBothMaps(key) : null;
}
private V removeFromBothMaps(Object key) {
V oldValue = delegate.remove(key);
removeFromInverseMap(oldValue);
return oldValue;
}
private void removeFromInverseMap(V oldValue) {
inverse.delegate.remove(oldValue);
}
// Bulk Operations
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override public void clear() {
delegate.clear();
inverse.delegate.clear();
}
// Views
@Override
public BiMap<V, K> inverse() {
return inverse;
}
private transient Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = new KeySet() : result;
}
private class KeySet extends ForwardingSet<K> {
@Override protected Set<K> delegate() {
return delegate.keySet();
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object key) {
if (!contains(key)) {
return false;
}
removeFromBothMaps(key);
return true;
}
@Override public boolean removeAll(Collection<?> keysToRemove) {
return standardRemoveAll(keysToRemove);
}
@Override public boolean retainAll(Collection<?> keysToRetain) {
return standardRetainAll(keysToRetain);
}
@Override public Iterator<K> iterator() {
return Maps.keyIterator(entrySet().iterator());
}
}
private transient Set<V> valueSet;
@Override public Set<V> values() {
/*
* We can almost reuse the inverse's keySet, except we have to fix the
* iteration order so that it is consistent with the forward map.
*/
Set<V> result = valueSet;
return (result == null) ? valueSet = new ValueSet() : result;
}
private class ValueSet extends ForwardingSet<V> {
final Set<V> valuesDelegate = inverse.keySet();
@Override protected Set<V> delegate() {
return valuesDelegate;
}
@Override public Iterator<V> iterator() {
return Maps.valueIterator(entrySet().iterator());
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public String toString() {
return standardToString();
}
}
private transient Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = new EntrySet() : result;
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
final Set<Entry<K, V>> esDelegate = delegate.entrySet();
@Override protected Set<Entry<K, V>> delegate() {
return esDelegate;
}
@Override public void clear() {
AbstractBiMap.this.clear();
}
@Override public boolean remove(Object object) {
if (!esDelegate.contains(object)) {
return false;
}
// safe because esDelgate.contains(object).
Entry<?, ?> entry = (Entry<?, ?>) object;
inverse.delegate.remove(entry.getValue());
/*
* Remove the mapping in inverse before removing from esDelegate because
* if entry is part of esDelegate, entry might be invalidated after the
* mapping is removed from esDelegate.
*/
esDelegate.remove(entry);
return true;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> iterator = esDelegate.iterator();
return new Iterator<Entry<K, V>>() {
Entry<K, V> entry;
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public Entry<K, V> next() {
entry = iterator.next();
final Entry<K, V> finalEntry = entry;
return new ForwardingMapEntry<K, V>() {
@Override protected Entry<K, V> delegate() {
return finalEntry;
}
@Override public V setValue(V value) {
// Preconditions keep the map and inverse consistent.
checkState(contains(this), "entry no longer in map");
// similar to putInBothMaps, but set via entry
if (Objects.equal(value, getValue())) {
return value;
}
checkArgument(!containsValue(value),
"value already present: %s", value);
V oldValue = finalEntry.setValue(value);
checkState(Objects.equal(value, get(getKey())),
"entry no longer in map");
updateInverseMap(getKey(), true, oldValue, value);
return oldValue;
}
};
}
@Override public void remove() {
checkState(entry != null);
V value = entry.getValue();
iterator.remove();
removeFromInverseMap(value);
}
};
}
// See java.util.Collections.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public boolean contains(Object o) {
return Maps.containsEntryImpl(delegate(), o);
}
@Override public boolean containsAll(Collection<?> c) {
return standardContainsAll(c);
}
@Override public boolean removeAll(Collection<?> c) {
return standardRemoveAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return standardRetainAll(c);
}
}
/** The inverse of any other {@code AbstractBiMap} subclass. */
private static class Inverse<K, V> extends AbstractBiMap<K, V> {
private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) {
super(backward, forward);
}
/*
* Serialization stores the forward bimap, the inverse of this inverse.
* Deserialization calls inverse() on the forward bimap and returns that
* inverse.
*
* If a bimap and its inverse are serialized together, the deserialized
* instances have inverse() methods that return the other.
*/
@Override
K checkKey(K key) {
return inverse.checkValue(key);
}
@Override
V checkValue(V value) {
return inverse.checkKey(value);
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* GWT implementation of {@link ImmutableMap} that forwards to another map.
*
* @author Hayward Chan
*/
public abstract class ForwardingImmutableMap<K, V> extends ImmutableMap<K, V> {
final transient Map<K, V> delegate;
ForwardingImmutableMap(Map<? extends K, ? extends V> delegate) {
this.delegate = Collections.unmodifiableMap(delegate);
}
@SuppressWarnings("unchecked")
ForwardingImmutableMap(Entry<? extends K, ? extends V>... entries) {
Map<K, V> delegate = Maps.newLinkedHashMap();
for (Entry<? extends K, ? extends V> entry : entries) {
K key = checkNotNull(entry.getKey());
V previous = delegate.put(key, checkNotNull(entry.getValue()));
if (previous != null) {
throw new IllegalArgumentException("duplicate key: " + key);
}
}
this.delegate = Collections.unmodifiableMap(delegate);
}
boolean isPartialView() {
return false;
}
public final boolean isEmpty() {
return delegate.isEmpty();
}
public final boolean containsKey(@Nullable Object key) {
return Maps.safeContainsKey(delegate, key);
}
public final boolean containsValue(@Nullable Object value) {
return delegate.containsValue(value);
}
public V get(@Nullable Object key) {
return (key == null) ? null : Maps.safeGet(delegate, key);
}
@Override ImmutableSet<Entry<K, V>> createEntrySet() {
return ImmutableSet.unsafeDelegate(
new ForwardingSet<Entry<K, V>>() {
@Override protected Set<Entry<K, V>> delegate() {
return delegate.entrySet();
}
@Override public boolean contains(Object object) {
if (object instanceof Entry<?, ?>
&& ((Entry<?, ?>) object).getKey() == null) {
return false;
}
try {
return super.contains(object);
} catch (ClassCastException e) {
return false;
}
}
@Override public <T> T[] toArray(T[] array) {
T[] result = super.toArray(array);
if (size() < result.length) {
// It works around a GWT bug where elements after last is not
// properly null'ed.
result[size()] = null;
}
return result;
}
});
}
@Override ImmutableSet<K> createKeySet() {
return ImmutableSet.unsafeDelegate(delegate.keySet());
}
@Override ImmutableCollection<V> createValues() {
return ImmutableCollection.unsafeDelegate(delegate.values());
}
@Override public int size() {
return delegate.size();
}
@Override public boolean equals(@Nullable Object object) {
return delegate.equals(object);
}
@Override public int hashCode() {
return delegate.hashCode();
}
@Override public String toString() {
return delegate.toString();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* An {@link ImmutableAsList} implementation specialized for when the delegate collection is
* already backed by an {@code ImmutableList} or array.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("serial") // uses writeReplace, not default serialization
class RegularImmutableAsList<E> extends ImmutableAsList<E> {
private final ImmutableCollection<E> delegate;
private final ImmutableList<? extends E> delegateList;
RegularImmutableAsList(ImmutableCollection<E> delegate, ImmutableList<? extends E> delegateList) {
this.delegate = delegate;
this.delegateList = delegateList;
}
RegularImmutableAsList(ImmutableCollection<E> delegate, Object[] array) {
this(delegate, ImmutableList.<E>asImmutableList(array));
}
@Override
ImmutableCollection<E> delegateCollection() {
return delegate;
}
ImmutableList<? extends E> delegateList() {
return delegateList;
}
@SuppressWarnings("unchecked") // safe covariant cast!
@Override
public UnmodifiableListIterator<E> listIterator(int index) {
return (UnmodifiableListIterator<E>) delegateList.listIterator(index);
}
@Override
public E get(int index) {
return delegateList.get(index);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import java.util.Comparator;
import java.util.SortedSet;
/**
* GWT emulation of {@code SortedMultiset}, with {@code elementSet} reduced
* to returning a {@code SortedSet} for GWT compatibility.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
public interface SortedMultiset<E> extends Multiset<E>, SortedIterable<E> {
Comparator<? super E> comparator();
Entry<E> firstEntry();
Entry<E> lastEntry();
Entry<E> pollFirstEntry();
Entry<E> pollLastEntry();
/**
* Returns a {@link SortedSet} view of the distinct elements in this multiset.
* (Outside GWT, this returns a {@code NavigableSet}.)
*/
@Override SortedSet<E> elementSet();
SortedMultiset<E> descendingMultiset();
SortedMultiset<E> headMultiset(E upperBound, BoundType boundType);
SortedMultiset<E> subMultiset(E lowerBound, BoundType lowerBoundType,
E upperBound, BoundType upperBoundType);
SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType);
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* GWT emulated version of {@link ImmutableSet}. For the unsorted sets, they
* are thin wrapper around {@link java.util.Collections#emptySet()}, {@link
* Collections#singleton(Object)} and {@link java.util.LinkedHashSet} for
* empty, singleton and regular sets respectively. For the sorted sets, it's
* a thin wrapper around {@link java.util.TreeSet}.
*
* @see ImmutableSortedSet
*
* @author Hayward Chan
*/
@SuppressWarnings("serial") // Serialization only done in GWT.
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
ImmutableSet() {}
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings({"unchecked"})
public static <E> ImmutableSet<E> of() {
return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE;
}
public static <E> ImmutableSet<E> of(E element) {
return new SingletonImmutableSet<E>(element);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> of(E e1, E e2) {
return create(e1, e2);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
return create(e1, e2, e3);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
return create(e1, e2, e3, e4);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
return create(e1, e2, e3, e4, e5);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
int size = others.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, others);
return copyOf(all.iterator());
}
/** @deprecated */
@Deprecated public static <E> ImmutableSet<E> of(E[] elements) {
return copyOf(elements);
}
public static <E> ImmutableSet<E> copyOf(E[] elements) {
checkNotNull(elements);
switch (elements.length) {
case 0:
return of();
case 1:
return of(elements[0]);
default:
return create(elements);
}
}
public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
Iterable<? extends E> iterable = elements;
return copyOf(iterable);
}
public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableSet<E> set = (ImmutableSet<E>) elements;
return set;
}
return copyOf(elements.iterator());
}
public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
if (!elements.hasNext()) {
return of();
}
E first = elements.next();
if (!elements.hasNext()) {
// TODO: Remove "ImmutableSet.<E>" when eclipse bug is fixed.
return ImmutableSet.<E>of(first);
}
Set<E> delegate = Sets.newLinkedHashSet();
delegate.add(checkNotNull(first));
do {
delegate.add(checkNotNull(elements.next()));
} while (elements.hasNext());
return unsafeDelegate(delegate);
}
// Factory methods that skips the null checks on elements, only used when
// the elements are known to be non-null.
static <E> ImmutableSet<E> unsafeDelegate(Set<E> delegate) {
switch (delegate.size()) {
case 0:
return of();
case 1:
return new SingletonImmutableSet<E>(delegate.iterator().next());
default:
return new RegularImmutableSet<E>(delegate);
}
}
private static <E> ImmutableSet<E> create(E... elements) {
// Create the set first, to remove duplicates if necessary.
Set<E> set = Sets.newLinkedHashSet();
Collections.addAll(set, elements);
for (E element : set) {
checkNotNull(element);
}
switch (set.size()) {
case 0:
return of();
case 1:
return new SingletonImmutableSet<E>(set.iterator().next());
default:
return new RegularImmutableSet<E>(set);
}
}
@Override public boolean equals(Object obj) {
return Sets.equalsImpl(this, obj);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
public static <E> Builder<E> builder() {
return new Builder<E>();
}
public static class Builder<E> extends ImmutableCollection.Builder<E> {
// accessed directly by ImmutableSortedSet
final ArrayList<E> contents = Lists.newArrayList();
public Builder() {}
@Override public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
@Override public Builder<E> add(E... elements) {
checkNotNull(elements); // for GWT
contents.ensureCapacity(contents.size() + elements.length);
super.add(elements);
return this;
}
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
Collection<?> collection = (Collection<?>) elements;
contents.ensureCapacity(contents.size() + collection.size());
}
super.addAll(elements);
return this;
}
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override public ImmutableSet<E> build() {
return copyOf(contents.iterator());
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
/**
* Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees
* induced by this traverser.
*
* <p>For example, the tree <pre> {@code
*
* h
* / | \
* / e \
* d g
* /|\ |
* / | \ f
* a b c
* }</pre>
*
* can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order
* (hdegabc).
*
* <p>Null nodes are strictly forbidden.
*
* @author Louis Wasserman
*/
public abstract class TreeTraverser<T> {
/**
* Returns the children of the specified node. Must not contain null.
*/
public abstract Iterable<T> children(T root);
/**
* Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order
* traversal. That is, each node's subtrees are traversed after the node itself is returned.
*
* <p>No guarantees are made about the behavior of the traversal when nodes change while
* iteration is in progress or when the iterators generated by {@link #children} are advanced.
*/
public final FluentIterable<T> preOrderTraversal(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public UnmodifiableIterator<T> iterator() {
return preOrderIterator(root);
}
};
}
// overridden in BinaryTreeTraverser
UnmodifiableIterator<T> preOrderIterator(T root) {
return new PreOrderIterator(root);
}
private final class PreOrderIterator extends UnmodifiableIterator<T> {
private final LinkedList<Iterator<T>> stack;
PreOrderIterator(T root) {
this.stack = Lists.newLinkedList();
stack.addLast(Iterators.singletonIterator(checkNotNull(root)));
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
Iterator<T> itr = stack.getLast(); // throws NSEE if empty
T result = checkNotNull(itr.next());
if (!itr.hasNext()) {
stack.removeLast();
}
Iterator<T> childItr = children(result).iterator();
if (childItr.hasNext()) {
stack.addLast(childItr);
}
return result;
}
}
/**
* Returns an unmodifiable iterable over the nodes in a tree structure, using post-order
* traversal. That is, each node's subtrees are traversed before the node itself is returned.
*
* <p>No guarantees are made about the behavior of the traversal when nodes change while
* iteration is in progress or when the iterators generated by {@link #children} are advanced.
*/
public final FluentIterable<T> postOrderTraversal(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public UnmodifiableIterator<T> iterator() {
return postOrderIterator(root);
}
};
}
// overridden in BinaryTreeTraverser
UnmodifiableIterator<T> postOrderIterator(T root) {
return new PostOrderIterator(root);
}
private static final class PostOrderNode<T> {
final T root;
final Iterator<T> childIterator;
PostOrderNode(T root, Iterator<T> childIterator) {
this.root = checkNotNull(root);
this.childIterator = checkNotNull(childIterator);
}
}
private final class PostOrderIterator extends AbstractIterator<T> {
private final LinkedList<PostOrderNode<T>> stack;
PostOrderIterator(T root) {
this.stack = Lists.newLinkedList();
stack.addLast(expand(root));
}
@Override
protected T computeNext() {
while (!stack.isEmpty()) {
PostOrderNode<T> top = stack.getLast();
if (top.childIterator.hasNext()) {
T child = top.childIterator.next();
stack.addLast(expand(child));
} else {
stack.removeLast();
return top.root;
}
}
return endOfData();
}
private PostOrderNode<T> expand(T t) {
return new PostOrderNode<T>(t, children(t).iterator());
}
}
/**
* Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first
* traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on.
*
* <p>No guarantees are made about the behavior of the traversal when nodes change while
* iteration is in progress or when the iterators generated by {@link #children} are advanced.
*/
public final FluentIterable<T> breadthFirstTraversal(final T root) {
checkNotNull(root);
return new FluentIterable<T>() {
@Override
public UnmodifiableIterator<T> iterator() {
return new BreadthFirstIterator(root);
}
};
}
private final class BreadthFirstIterator extends UnmodifiableIterator<T>
implements PeekingIterator<T> {
private final Queue<T> queue;
BreadthFirstIterator(T root) {
this.queue = Lists.newLinkedList();
queue.add(checkNotNull(root));
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
public T peek() {
return queue.element();
}
@Override
public T next() {
T result = queue.remove();
for (T child : children(result)) {
queue.add(checkNotNull(child));
}
return result;
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.collect.Multisets.UnmodifiableMultiset;
import java.util.Collections;
import java.util.Comparator;
import java.util.SortedSet;
/**
* Implementation of {@link Multisets#unmodifiableSortedMultiset(SortedMultiset)}
* for GWT.
*
* @author Louis Wasserman
*/
final class UnmodifiableSortedMultiset<E>
extends UnmodifiableMultiset<E> implements SortedMultiset<E> {
UnmodifiableSortedMultiset(SortedMultiset<E> delegate) {
super(delegate);
}
@Override
protected SortedMultiset<E> delegate() {
return (SortedMultiset<E>) super.delegate();
}
@Override
public Comparator<? super E> comparator() {
return delegate().comparator();
}
@Override
SortedSet<E> createElementSet() {
return Collections.unmodifiableSortedSet(delegate().elementSet());
}
@Override
public SortedSet<E> elementSet() {
return (SortedSet<E>) super.elementSet();
}
private transient UnmodifiableSortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
UnmodifiableSortedMultiset<E> result = descendingMultiset;
if (result == null) {
result = new UnmodifiableSortedMultiset<E>(
delegate().descendingMultiset());
result.descendingMultiset = this;
return descendingMultiset = result;
}
return result;
}
@Override
public Entry<E> firstEntry() {
return delegate().firstEntry();
}
@Override
public Entry<E> lastEntry() {
return delegate().lastEntry();
}
@Override
public Entry<E> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public Entry<E> pollLastEntry() {
throw new UnsupportedOperationException();
}
@Override
public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return Multisets.unmodifiableSortedMultiset(
delegate().headMultiset(upperBound, boundType));
}
@Override
public SortedMultiset<E> subMultiset(
E lowerBound, BoundType lowerBoundType,
E upperBound, BoundType upperBoundType) {
return Multisets.unmodifiableSortedMultiset(delegate().subMultiset(
lowerBound, lowerBoundType, upperBound, upperBoundType));
}
@Override
public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return Multisets.unmodifiableSortedMultiset(
delegate().tailMultiset(lowerBound, boundType));
}
private static final long serialVersionUID = 0;
} | Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* This class provides a skeletal implementation of the {@link SortedMultiset} interface.
*
* <p>The {@link #count} and {@link #size} implementations all iterate across the set returned by
* {@link Multiset#entrySet()}, as do many methods acting on the set returned by
* {@link #elementSet()}. Override those methods for better performance.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class AbstractSortedMultiset<E> extends AbstractMultiset<E> implements SortedMultiset<E> {
@GwtTransient final Comparator<? super E> comparator;
// needed for serialization
@SuppressWarnings("unchecked")
AbstractSortedMultiset() {
this((Comparator) Ordering.natural());
}
AbstractSortedMultiset(Comparator<? super E> comparator) {
this.comparator = checkNotNull(comparator);
}
@Override
public SortedSet<E> elementSet() {
return (SortedSet<E>) super.elementSet();
}
@Override
SortedSet<E> createElementSet() {
return new SortedMultisets.ElementSet<E>(this);
}
@Override
public Comparator<? super E> comparator() {
return comparator;
}
@Override
public Entry<E> firstEntry() {
Iterator<Entry<E>> entryIterator = entryIterator();
return entryIterator.hasNext() ? entryIterator.next() : null;
}
@Override
public Entry<E> lastEntry() {
Iterator<Entry<E>> entryIterator = descendingEntryIterator();
return entryIterator.hasNext() ? entryIterator.next() : null;
}
@Override
public Entry<E> pollFirstEntry() {
Iterator<Entry<E>> entryIterator = entryIterator();
if (entryIterator.hasNext()) {
Entry<E> result = entryIterator.next();
result = Multisets.immutableEntry(result.getElement(), result.getCount());
entryIterator.remove();
return result;
}
return null;
}
@Override
public Entry<E> pollLastEntry() {
Iterator<Entry<E>> entryIterator = descendingEntryIterator();
if (entryIterator.hasNext()) {
Entry<E> result = entryIterator.next();
result = Multisets.immutableEntry(result.getElement(), result.getCount());
entryIterator.remove();
return result;
}
return null;
}
@Override
public SortedMultiset<E> subMultiset(@Nullable E fromElement, BoundType fromBoundType,
@Nullable E toElement, BoundType toBoundType) {
// These are checked elsewhere, but NullPointerTester wants them checked eagerly.
checkNotNull(fromBoundType);
checkNotNull(toBoundType);
return tailMultiset(fromElement, fromBoundType).headMultiset(toElement, toBoundType);
}
abstract Iterator<Entry<E>> descendingEntryIterator();
Iterator<E> descendingIterator() {
return Multisets.iteratorImpl(descendingMultiset());
}
private transient SortedMultiset<E> descendingMultiset;
@Override
public SortedMultiset<E> descendingMultiset() {
SortedMultiset<E> result = descendingMultiset;
return (result == null) ? descendingMultiset = createDescendingMultiset() : result;
}
SortedMultiset<E> createDescendingMultiset() {
return new DescendingMultiset<E>() {
@Override
SortedMultiset<E> forwardMultiset() {
return AbstractSortedMultiset.this;
}
@Override
Iterator<Entry<E>> entryIterator() {
return descendingEntryIterator();
}
@Override
public Iterator<E> iterator() {
return descendingIterator();
}
};
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.LinkedHashMap;
/**
* A {@code Multiset} implementation with predictable iteration order. Its
* iterator orders elements according to when the first occurrence of the
* element was added. When the multiset contains multiple instances of an
* element, those instances are consecutive in the iteration order. If all
* occurrences of an element are removed, after which that element is added to
* the multiset, the element will appear at the end of the iteration.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> {
/**
* Creates a new, empty {@code LinkedHashMultiset} using the default initial
* capacity.
*/
public static <E> LinkedHashMultiset<E> create() {
return new LinkedHashMultiset<E>();
}
/**
* Creates a new, empty {@code LinkedHashMultiset} with the specified expected
* number of distinct elements.
*
* @param distinctElements the expected number of distinct elements
* @throws IllegalArgumentException if {@code distinctElements} is negative
*/
public static <E> LinkedHashMultiset<E> create(int distinctElements) {
return new LinkedHashMultiset<E>(distinctElements);
}
/**
* Creates a new {@code LinkedHashMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself
* a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> LinkedHashMultiset<E> create(
Iterable<? extends E> elements) {
LinkedHashMultiset<E> multiset =
create(Multisets.inferDistinctElements(elements));
Iterables.addAll(multiset, elements);
return multiset;
}
private LinkedHashMultiset() {
super(new LinkedHashMap<E, Count>());
}
private LinkedHashMultiset(int distinctElements) {
// Could use newLinkedHashMapWithExpectedSize() if it existed
super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements)));
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* List returned by {@link ImmutableCollection#asList} that delegates {@code contains} checks
* to the backing collection.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial")
abstract class ImmutableAsList<E> extends ImmutableList<E> {
abstract ImmutableCollection<E> delegateCollection();
@Override public boolean contains(Object target) {
// The collection's contains() is at least as fast as ImmutableList's
// and is often faster.
return delegateCollection().contains(target);
}
@Override
public int size() {
return delegateCollection().size();
}
@Override
public boolean isEmpty() {
return delegateCollection().isEmpty();
}
@Override
boolean isPartialView() {
return delegateCollection().isPartialView();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Objects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* An immutable {@link SetMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableSetMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableSetMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Mike Ward
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableSetMultimap<K, V>
extends ImmutableMultimap<K, V>
implements SetMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSetMultimap<K, V> of() {
return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
* Repeated occurrences of an entry (according to {@link Object#equals}) after
* the first are ignored.
*/
public static <K, V> ImmutableSetMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new {@link Builder}.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableSetMultimap.Builder} that maintains key
* and value orderings and performs better than {@link LinkedHashMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Sets.newLinkedHashSet();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable {@code SetMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableSetMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<K, V>
extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSetMultimap#builder}.
*/
public Builder() {
builderMultimap = new BuilderMultimap<K, V>();
}
/**
* Adds a key-value mapping to the built multimap if it is not already
* present.
*/
@Override public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap if it is not already present.
*
* @since 11.0
*/
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> collection = builderMultimap.get(checkNotNull(key));
for (V value : values) {
collection.add(checkNotNull(value));
}
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* <p>If this method is called, the sets returned by the {@code get()}
* method of the generated multimap and its {@link Multimap#asMap()} view
* are {@link ImmutableSortedSet} instances. However, serialization does not
* preserve that property, though it does maintain the key and value
* ordering.
*
* @since 8.0
*/
// TODO: Make serialization behavior consistent.
@Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable set multimap.
*/
@Override public ImmutableSetMultimap<K, V> build() {
if (keyComparator != null) {
Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
builderMultimap.asMap().entrySet());
Collections.sort(
entries,
Ordering.from(keyComparator).<K>onKeys());
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap, valueComparator);
}
}
/**
* Returns an immutable set multimap containing the same mappings as
* {@code multimap}. The generated multimap's key and value orderings
* correspond to the iteration ordering of the {@code multimap.asMap()} view.
* Repeated occurrences of an entry in the multimap after the first are
* ignored.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
return copyOf(multimap, null);
}
private static <K, V> ImmutableSetMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap,
Comparator<? super V> valueComparator) {
checkNotNull(multimap); // eager for GWT
if (multimap.isEmpty() && valueComparator == null) {
return of();
}
if (multimap instanceof ImmutableSetMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableSetMultimap<K, V> kvMultimap
= (ImmutableSetMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
K key = entry.getKey();
Collection<? extends V> values = entry.getValue();
ImmutableSet<V> set = valueSet(valueComparator, values);
if (!set.isEmpty()) {
builder.put(key, set);
size += set.size();
}
}
return new ImmutableSetMultimap<K, V>(
builder.build(), size, valueComparator);
}
/**
* Returned by get() when a missing key is provided. Also holds the
* comparator, if any, used for values.
*/
private final transient ImmutableSet<V> emptySet;
ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size,
@Nullable Comparator<? super V> valueComparator) {
super(map, size);
this.emptySet = emptySet(valueComparator);
}
// views
/**
* Returns an immutable set of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable set is returned.
* The values are in the same order as the parameters used to build this
* multimap.
*/
@Override public ImmutableSet<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableSet<V> set = (ImmutableSet<V>) map.get(key);
return firstNonNull(set, emptySet);
}
private transient ImmutableSetMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a set multimap cannot contain multiple pairs with
* the same key and value, this method returns an {@code ImmutableSetMultimap}
* rather than the {@code ImmutableMultimap} specified in the {@code
* ImmutableMultimap} class.
*
* @since 11.0
*/
public ImmutableSetMultimap<V, K> inverse() {
ImmutableSetMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableSetMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableSetMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private transient ImmutableSet<Entry<K, V>> entries;
/**
* Returns an immutable collection of all key-value pairs in the multimap.
* Its iterator traverses the values for the first key, the values for the
* second key, and so on.
*/
@Override public ImmutableSet<Entry<K, V>> entries() {
ImmutableSet<Entry<K, V>> result = entries;
return (result == null)
? (entries = new EntrySet<K, V>(this))
: result;
}
private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
private transient final ImmutableSetMultimap<K, V> multimap;
EntrySet(ImmutableSetMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override
public boolean contains(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override
public int size() {
return multimap.size();
}
@Override
public UnmodifiableIterator<Entry<K, V>> iterator() {
return multimap.entryIterator();
}
@Override
boolean isPartialView() {
return false;
}
}
private static <V> ImmutableSet<V> valueSet(
@Nullable Comparator<? super V> valueComparator,
Collection<? extends V> values) {
return (valueComparator == null)
? ImmutableSet.copyOf(values)
: ImmutableSortedSet.copyOf(valueComparator, values);
}
private static <V> ImmutableSet<V> emptySet(
@Nullable Comparator<? super V> valueComparator) {
return (valueComparator == null)
? ImmutableSet.<V>of()
: ImmutableSortedSet.<V>emptySet(valueComparator);
}
@Nullable Comparator<? super V> valueComparator() {
return emptySet instanceof ImmutableSortedSet
? ((ImmutableSortedSet<V>) emptySet).comparator()
: null;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import javax.annotation.Nullable;
/**
* This class contains static utility methods that operate on or return objects
* of type {@code Iterable}. Except as noted, each method has a corresponding
* {@link Iterator}-based method in the {@link Iterators} class.
*
* <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables
* produced in this class are <i>lazy</i>, which means that their iterators
* only advance the backing iteration when absolutely necessary.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables">
* {@code Iterables}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Iterables {
private Iterables() {}
/** Returns an unmodifiable view of {@code iterable}. */
public static <T> Iterable<T> unmodifiableIterable(
final Iterable<T> iterable) {
checkNotNull(iterable);
if (iterable instanceof UnmodifiableIterable ||
iterable instanceof ImmutableCollection) {
return iterable;
}
return new UnmodifiableIterable<T>(iterable);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <E> Iterable<E> unmodifiableIterable(
ImmutableCollection<E> iterable) {
return checkNotNull(iterable);
}
private static final class UnmodifiableIterable<T> extends FluentIterable<T> {
private final Iterable<T> iterable;
private UnmodifiableIterable(Iterable<T> iterable) {
this.iterable = iterable;
}
@Override
public Iterator<T> iterator() {
return Iterators.unmodifiableIterator(iterable.iterator());
}
@Override
public String toString() {
return iterable.toString();
}
// no equals and hashCode; it would break the contract!
}
/**
* Returns the number of elements in {@code iterable}.
*/
public static int size(Iterable<?> iterable) {
return (iterable instanceof Collection)
? ((Collection<?>) iterable).size()
: Iterators.size(iterable.iterator());
}
/**
* Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)}
* is true.
*/
public static boolean contains(Iterable<?> iterable, @Nullable Object element)
{
if (iterable instanceof Collection) {
Collection<?> collection = (Collection<?>) iterable;
return Collections2.safeContains(collection, element);
}
return Iterators.contains(iterable.iterator(), element);
}
/**
* Removes, from an iterable, every element that belongs to the provided
* collection.
*
* <p>This method calls {@link Collection#removeAll} if {@code iterable} is a
* collection, and {@link Iterators#removeAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean removeAll(
Iterable<?> removeFrom, Collection<?> elementsToRemove) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove))
: Iterators.removeAll(removeFrom.iterator(), elementsToRemove);
}
/**
* Removes, from an iterable, every element that does not belong to the
* provided collection.
*
* <p>This method calls {@link Collection#retainAll} if {@code iterable} is a
* collection, and {@link Iterators#retainAll} otherwise.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterable}
*/
public static boolean retainAll(
Iterable<?> removeFrom, Collection<?> elementsToRetain) {
return (removeFrom instanceof Collection)
? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain))
: Iterators.retainAll(removeFrom.iterator(), elementsToRetain);
}
/**
* Removes, from an iterable, every element that satisfies the provided
* predicate.
*
* @param removeFrom the iterable to (potentially) remove elements from
* @param predicate a predicate that determines whether an element should
* be removed
* @return {@code true} if any elements were removed from the iterable
*
* @throws UnsupportedOperationException if the iterable does not support
* {@code remove()}.
* @since 2.0
*/
public static <T> boolean removeIf(
Iterable<T> removeFrom, Predicate<? super T> predicate) {
if (removeFrom instanceof RandomAccess && removeFrom instanceof List) {
return removeIfFromRandomAccessList(
(List<T>) removeFrom, checkNotNull(predicate));
}
return Iterators.removeIf(removeFrom.iterator(), predicate);
}
private static <T> boolean removeIfFromRandomAccessList(
List<T> list, Predicate<? super T> predicate) {
// Note: Not all random access lists support set() so we need to deal with
// those that don't and attempt the slower remove() based solution.
int from = 0;
int to = 0;
for (; from < list.size(); from++) {
T element = list.get(from);
if (!predicate.apply(element)) {
if (from > to) {
try {
list.set(to, element);
} catch (UnsupportedOperationException e) {
slowRemoveIfForRemainingElements(list, predicate, to, from);
return true;
}
}
to++;
}
}
// Clear the tail of any remaining items
list.subList(to, list.size()).clear();
return from != to;
}
private static <T> void slowRemoveIfForRemainingElements(List<T> list,
Predicate<? super T> predicate, int to, int from) {
// Here we know that:
// * (to < from) and that both are valid indices.
// * Everything with (index < to) should be kept.
// * Everything with (to <= index < from) should be removed.
// * The element with (index == from) should be kept.
// * Everything with (index > from) has not been checked yet.
// Check from the end of the list backwards (minimize expected cost of
// moving elements when remove() is called). Stop before 'from' because
// we already know that should be kept.
for (int n = list.size() - 1; n > from; n--) {
if (predicate.apply(list.get(n))) {
list.remove(n);
}
}
// And now remove everything in the range [to, from) (going backwards).
for (int n = from - 1; n >= to; n--) {
list.remove(n);
}
}
/**
* Removes and returns the first matching element, or returns {@code null} if there is none.
*/
@Nullable
static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
Iterator<T> iterator = removeFrom.iterator();
while (iterator.hasNext()) {
T next = iterator.next();
if (predicate.apply(next)) {
iterator.remove();
return next;
}
}
return null;
}
/**
* Determines whether two iterables contain equal elements in the same order.
* More specifically, this method returns {@code true} if {@code iterable1}
* and {@code iterable2} contain the same number of elements and every element
* of {@code iterable1} is equal to the corresponding element of
* {@code iterable2}.
*/
public static boolean elementsEqual(
Iterable<?> iterable1, Iterable<?> iterable2) {
if (iterable1 instanceof Collection && iterable2 instanceof Collection) {
Collection<?> collection1 = (Collection<?>) iterable1;
Collection<?> collection2 = (Collection<?>) iterable2;
if (collection1.size() != collection2.size()) {
return false;
}
}
return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator());
}
/**
* Returns a string representation of {@code iterable}, with the format
* {@code [e1, e2, ..., en]}.
*/
public static String toString(Iterable<?> iterable) {
return Iterators.toString(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}.
*
* @throws NoSuchElementException if the iterable is empty
* @throws IllegalArgumentException if the iterable contains multiple
* elements
*/
public static <T> T getOnlyElement(Iterable<T> iterable) {
return Iterators.getOnlyElement(iterable.iterator());
}
/**
* Returns the single element contained in {@code iterable}, or {@code
* defaultValue} if the iterable is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple
* elements
*/
@Nullable
public static <T> T getOnlyElement(
Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getOnlyElement(iterable.iterator(), defaultValue);
}
/**
* Copies an iterable's elements into an array.
*
* @param iterable the iterable to copy
* @return a newly-allocated array into which all the elements of the iterable
* have been copied
*/
static Object[] toArray(Iterable<?> iterable) {
return toCollection(iterable).toArray();
}
/**
* Converts an iterable into a collection. If the iterable is already a
* collection, it is returned. Otherwise, an {@link java.util.ArrayList} is
* created with the contents of the iterable in the same iteration order.
*/
private static <E> Collection<E> toCollection(Iterable<E> iterable) {
return (iterable instanceof Collection)
? (Collection<E>) iterable
: Lists.newArrayList(iterable.iterator());
}
/**
* Adds all elements in {@code iterable} to {@code collection}.
*
* @return {@code true} if {@code collection} was modified as a result of this
* operation.
*/
public static <T> boolean addAll(
Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
if (elementsToAdd instanceof Collection) {
Collection<? extends T> c = Collections2.cast(elementsToAdd);
return addTo.addAll(c);
}
return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator());
}
/**
* Returns the number of elements in the specified iterable that equal the
* specified object. This implementation avoids a full iteration when the
* iterable is a {@link Multiset} or {@link Set}.
*
* @see Collections#frequency
*/
public static int frequency(Iterable<?> iterable, @Nullable Object element) {
if ((iterable instanceof Multiset)) {
return ((Multiset<?>) iterable).count(element);
} else if ((iterable instanceof Set)) {
return ((Set<?>) iterable).contains(element) ? 1 : 0;
}
return Iterators.frequency(iterable.iterator(), element);
}
/**
* Returns an iterable whose iterators cycle indefinitely over the elements of
* {@code iterable}.
*
* <p>That iterator supports {@code remove()} if {@code iterable.iterator()}
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, which is no longer in {@code iterable}. The iterator's
* {@code hasNext()} method returns {@code true} until {@code iterable} is
* empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*
* <p>To cycle over the iterable {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, iterable))}
*/
public static <T> Iterable<T> cycle(final Iterable<T> iterable) {
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.cycle(iterable);
}
@Override public String toString() {
return iterable.toString() + " (cycled)";
}
};
}
/**
* Returns an iterable whose iterators cycle indefinitely over the provided
* elements.
*
* <p>After {@code remove} is invoked on a generated iterator, the removed
* element will no longer appear in either that iterator or any other iterator
* created from the same source iterable. That is, this method behaves exactly
* as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's
* {@code hasNext} method returns {@code true} until all of the original
* elements have been removed.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*
* <p>To cycle over the elements {@code n} times, use the following:
* {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))}
*/
public static <T> Iterable<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Combines two iterables into a single iterable. The returned iterable has an
* iterator that traverses the elements in {@code a}, followed by the elements
* in {@code b}. The source iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(
Iterable<? extends T> a, Iterable<? extends T> b) {
return concat(ImmutableList.of(a, b));
}
/**
* Combines three iterables into a single iterable. The returned iterable has
* an iterator that traverses the elements in {@code a}, followed by the
* elements in {@code b}, followed by the elements in {@code c}. The source
* iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c) {
return concat(ImmutableList.of(a, b, c));
}
/**
* Combines four iterables into a single iterable. The returned iterable has
* an iterator that traverses the elements in {@code a}, followed by the
* elements in {@code b}, followed by the elements in {@code c}, followed by
* the elements in {@code d}. The source iterators are not polled until
* necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*/
public static <T> Iterable<T> concat(Iterable<? extends T> a,
Iterable<? extends T> b, Iterable<? extends T> c,
Iterable<? extends T> d) {
return concat(ImmutableList.of(a, b, c, d));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it.
*
* @throws NullPointerException if any of the provided iterables is null
*/
public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) {
return concat(ImmutableList.copyOf(inputs));
}
/**
* Combines multiple iterables into a single iterable. The returned iterable
* has an iterator that traverses the elements of each iterable in
* {@code inputs}. The input iterators are not polled until necessary.
*
* <p>The returned iterable's iterator supports {@code remove()} when the
* corresponding input iterator supports it. The methods of the returned
* iterable may throw {@code NullPointerException} if any of the input
* iterators is null.
*/
public static <T> Iterable<T> concat(
final Iterable<? extends Iterable<? extends T>> inputs) {
checkNotNull(inputs);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.concat(iterators(inputs));
}
};
}
/**
* Returns an iterator over the iterators of the given iterables.
*/
private static <T> Iterator<Iterator<? extends T>> iterators(
Iterable<? extends Iterable<? extends T>> iterables) {
return new TransformedIterator<Iterable<? extends T>, Iterator<? extends T>>(
iterables.iterator()) {
@Override
Iterator<? extends T> transform(Iterable<? extends T> from) {
return from.iterator();
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size (the final
* iterable may be smaller). For example, partitioning an iterable containing
* {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
* [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of
* three and two elements, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method. The returned lists implement {@link
* RandomAccess}, whether or not the input list does.
*
* <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link
* Lists#partition(List, int)} instead.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> partition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.partition(iterable.iterator(), size);
}
};
}
/**
* Divides an iterable into unmodifiable sublists of the given size, padding
* the final iterable with null values if necessary. For example, partitioning
* an iterable containing {@code [a, b, c, d, e]} with a partition size of 3
* yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing
* two inner lists of three elements each, all in the original order.
*
* <p>Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method.
*
* @param iterable the iterable to return a partitioned view of
* @param size the desired size of each partition
* @return an iterable of unmodifiable lists containing the elements of {@code
* iterable} divided into partitions (the final iterable may have
* trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> Iterable<List<T>> paddedPartition(
final Iterable<T> iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new FluentIterable<List<T>>() {
@Override
public Iterator<List<T>> iterator() {
return Iterators.paddedPartition(iterable.iterator(), size);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* resulting iterable's iterator does not support {@code remove()}.
*/
public static <T> Iterable<T> filter(
final Iterable<T> unfiltered, final Predicate<? super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.filter(unfiltered.iterator(), predicate);
}
};
}
/**
* Returns {@code true} if any element in {@code iterable} satisfies the predicate.
*/
public static <T> boolean any(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.any(iterable.iterator(), predicate);
}
/**
* Returns {@code true} if every element in {@code iterable} satisfies the
* predicate. If {@code iterable} is empty, {@code true} is returned.
*/
public static <T> boolean all(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.all(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate; use this method only when such an element is known to exist. If
* it is possible that <i>no</i> element will match, use {@link #tryFind} or
* {@link #find(Iterable, Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterable} matches
* the given predicate
*/
public static <T> T find(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.find(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate, or {@code defaultValue} if none found. Note that this can
* usually be handled more naturally using {@code
* tryFind(iterable, predicate).or(defaultValue)}.
*
* @since 7.0
*/
@Nullable
public static <T> T find(Iterable<? extends T> iterable,
Predicate<? super T> predicate, @Nullable T defaultValue) {
return Iterators.find(iterable.iterator(), predicate, defaultValue);
}
/**
* Returns an {@link Optional} containing the first element in {@code
* iterable} that satisfies the given predicate, if such an element exists.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
* null}. If {@code null} is matched in {@code iterable}, a
* NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(Iterable<T> iterable,
Predicate<? super T> predicate) {
return Iterators.tryFind(iterable.iterator(), predicate);
}
/**
* Returns the index in {@code iterable} of the first element that satisfies
* the provided {@code predicate}, or {@code -1} if the Iterable has no such
* elements.
*
* <p>More formally, returns the lowest index {@code i} such that
* {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true},
* or {@code -1} if there is no such index.
*
* @since 2.0
*/
public static <T> int indexOf(
Iterable<T> iterable, Predicate<? super T> predicate) {
return Iterators.indexOf(iterable.iterator(), predicate);
}
/**
* Returns an iterable that applies {@code function} to each element of {@code
* fromIterable}.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* provided iterator does. After a successful {@code remove()} call,
* {@code fromIterable} no longer contains the corresponding element.
*
* <p>If the input {@code Iterable} is known to be a {@code List} or other
* {@code Collection}, consider {@link Lists#transform} and {@link
* Collections2#transform}.
*/
public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable,
final Function<? super F, ? extends T> function) {
checkNotNull(fromIterable);
checkNotNull(function);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.transform(fromIterable.iterator(), function);
}
};
}
/**
* Returns the element at the specified position in an iterable.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterable}
* @throws IndexOutOfBoundsException if {@code position} is negative or
* greater than or equal to the size of {@code iterable}
*/
public static <T> T get(Iterable<T> iterable, int position) {
checkNotNull(iterable);
return (iterable instanceof List)
? ((List<T>) iterable).get(position)
: Iterators.get(iterable.iterator(), position);
}
/**
* Returns the element at the specified position in an iterable or a default
* value otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if {@code position} is
* greater than or equal to the size of the iterable
* @return the element at the specified position in {@code iterable} or
* {@code defaultValue} if {@code iterable} contains fewer than
* {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@Nullable
public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) {
checkNotNull(iterable);
Iterators.checkNonnegative(position);
if (iterable instanceof List) {
List<? extends T> list = Lists.cast(iterable);
return (position < list.size()) ? list.get(position) : defaultValue;
} else {
Iterator<? extends T> iterator = iterable.iterator();
Iterators.advance(iterator, position);
return Iterators.getNext(iterator, defaultValue);
}
}
/**
* Returns the first element in {@code iterable} or {@code defaultValue} if
* the iterable is empty. The {@link Iterators} analog to this method is
* {@link Iterators#getNext}.
*
* <p>If no default value is desired (and the caller instead wants a
* {@link NoSuchElementException} to be thrown), it is recommended that
* {@code iterable.iterator().next()} is used instead.
*
* @param defaultValue the default value to return if the iterable is empty
* @return the first element of {@code iterable} or the default value
* @since 7.0
*/
@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) {
return Iterators.getNext(iterable.iterator(), defaultValue);
}
/**
* Returns the last element of {@code iterable}.
*
* @return the last element of {@code iterable}
* @throws NoSuchElementException if the iterable is empty
*/
public static <T> T getLast(Iterable<T> iterable) {
// TODO(kevinb): Support a concurrently modified collection?
if (iterable instanceof List) {
List<T> list = (List<T>) iterable;
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return getLastInNonemptyList(list);
}
return Iterators.getLast(iterable.iterator());
}
/**
* Returns the last element of {@code iterable} or {@code defaultValue} if
* the iterable is empty.
*
* @param defaultValue the value to return if {@code iterable} is empty
* @return the last element of {@code iterable} or the default value
* @since 3.0
*/
@Nullable
public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) {
if (iterable instanceof Collection) {
Collection<? extends T> c = Collections2.cast(iterable);
if (c.isEmpty()) {
return defaultValue;
} else if (iterable instanceof List) {
return getLastInNonemptyList(Lists.cast(iterable));
}
}
return Iterators.getLast(iterable.iterator(), defaultValue);
}
private static <T> T getLastInNonemptyList(List<T> list) {
return list.get(list.size() - 1);
}
/**
* Returns a view of {@code iterable} that skips its first
* {@code numberToSkip} elements. If {@code iterable} contains fewer than
* {@code numberToSkip} elements, the returned iterable skips all of its
* elements.
*
* <p>Modifications to the underlying {@link Iterable} before a call to
* {@code iterator()} are reflected in the returned iterator. That is, the
* iterator skips the first {@code numberToSkip} elements that exist when the
* {@code Iterator} is created, not when {@code skip()} is called.
*
* <p>The returned iterable's iterator supports {@code remove()} if the
* iterator of the underlying iterable supports it. Note that it is
* <i>not</i> possible to delete the last skipped element by immediately
* calling {@code remove()} on that iterator, as the {@code Iterator}
* contract states that a call to {@code remove()} before a call to
* {@code next()} will throw an {@link IllegalStateException}.
*
* @since 3.0
*/
public static <T> Iterable<T> skip(final Iterable<T> iterable,
final int numberToSkip) {
checkNotNull(iterable);
checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
if (iterable instanceof List) {
final List<T> list = (List<T>) iterable;
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
// TODO(kevinb): Support a concurrently modified collection?
int toSkip = Math.min(list.size(), numberToSkip);
return list.subList(toSkip, list.size()).iterator();
}
};
}
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
final Iterator<T> iterator = iterable.iterator();
Iterators.advance(iterator, numberToSkip);
/*
* We can't just return the iterator because an immediate call to its
* remove() method would remove one of the skipped elements instead of
* throwing an IllegalStateException.
*/
return new Iterator<T>() {
boolean atStart = true;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
T result = iterator.next();
atStart = false; // not called if next() fails
return result;
}
@Override
public void remove() {
Iterators.checkRemove(!atStart);
iterator.remove();
}
};
}
};
}
/**
* Creates an iterable with the first {@code limitSize} elements of the given
* iterable. If the original iterable does not contain that many elements, the
* returned iterator will have the same behavior as the original iterable. The
* returned iterable's iterator supports {@code remove()} if the original
* iterator does.
*
* @param iterable the iterable to limit
* @param limitSize the maximum number of elements in the returned iterator
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T> Iterable<T> limit(
final Iterable<T> iterable, final int limitSize) {
checkNotNull(iterable);
checkArgument(limitSize >= 0, "limit is negative");
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.limit(iterable.iterator(), limitSize);
}
};
}
/**
* Returns a view of the supplied iterable that wraps each generated
* {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}.
*
* <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will
* get entries from {@link Queue#remove()} since {@link Queue}'s iteration
* order is undefined. Calling {@link Iterator#hasNext()} on a generated
* iterator from the returned iterable may cause an item to be immediately
* dequeued for return on a subsequent call to {@link Iterator#next()}.
*
* @param iterable the iterable to wrap
* @return a view of the supplied iterable that wraps each generated iterator
* through {@link Iterators#consumingIterator(Iterator)}; for queues,
* an iterable that generates iterators that return and consume the
* queue's elements in queue order
*
* @see Iterators#consumingIterator(Iterator)
* @since 2.0
*/
public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) {
if (iterable instanceof Queue) {
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return new ConsumingQueueIterator<T>((Queue<T>) iterable);
}
};
}
checkNotNull(iterable);
return new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.consumingIterator(iterable.iterator());
}
};
}
private static class ConsumingQueueIterator<T> extends AbstractIterator<T> {
private final Queue<T> queue;
private ConsumingQueueIterator(Queue<T> queue) {
this.queue = queue;
}
@Override public T computeNext() {
try {
return queue.remove();
} catch (NoSuchElementException e) {
return endOfData();
}
}
}
// Methods only in Iterables, not in Iterators
/**
* Determines if the given iterable contains no elements.
*
* <p>There is no precise {@link Iterator} equivalent to this method, since
* one can only ask an iterator whether it has any elements <i>remaining</i>
* (which one does using {@link Iterator#hasNext}).
*
* @return {@code true} if the iterable contains no elements
*/
public static boolean isEmpty(Iterable<?> iterable) {
if (iterable instanceof Collection) {
return ((Collection<?>) iterable).isEmpty();
}
return !iterable.iterator().hasNext();
}
/**
* Returns an iterable over the merged contents of all given
* {@code iterables}. Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterables} are in
* non-descending order as this method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterables}, it is
* undefined which element is returned first.
*
* @since 11.0
*/
@Beta
public static <T> Iterable<T> mergeSorted(
final Iterable<? extends Iterable<? extends T>> iterables,
final Comparator<? super T> comparator) {
checkNotNull(iterables, "iterables");
checkNotNull(comparator, "comparator");
Iterable<T> iterable = new FluentIterable<T>() {
@Override
public Iterator<T> iterator() {
return Iterators.mergeSorted(
Iterables.transform(iterables, Iterables.<T>toIterator()),
comparator);
}
};
return new UnmodifiableIterable<T>(iterable);
}
// TODO(user): Is this the best place for this? Move to fluent functions?
// Useful as a public method?
private static <T> Function<Iterable<? extends T>, Iterator<? extends T>>
toIterator() {
return new Function<Iterable<? extends T>, Iterator<? extends T>>() {
@Override
public Iterator<? extends T> apply(Iterable<? extends T> iterable) {
return iterable.iterator();
}
};
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Set} instances. Also see this
* class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets">
* {@code Sets}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Chris Povirk
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Sets {
private Sets() {}
/**
* {@link AbstractSet} substitute without the potentially-quadratic
* {@code removeAll} implementation.
*/
abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
@Override
public boolean removeAll(Collection<?> c) {
return removeAllImpl(this, c);
}
@Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(checkNotNull(c)); // GWT compatibility
}
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements are provided to the method.
*
* @param anElement one of the elements the set should contain
* @param otherElements the rest of the elements the set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
E anElement, E... otherElements) {
return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
}
/**
* Returns an immutable set instance containing the given enum elements.
* Internally, the returned set will be backed by an {@link EnumSet}.
*
* <p>The iteration order of the returned set follows the enum's iteration
* order, not the order in which the elements appear in the given collection.
*
* @param elements the elements, all of the same {@code enum} type, that the
* set should contain
* @return an immutable set containing those elements, minus duplicates
*/
// http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
@GwtCompatible(serializable = true)
public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
Iterable<E> elements) {
if (elements instanceof ImmutableEnumSet) {
return (ImmutableEnumSet<E>) elements;
} else if (elements instanceof Collection) {
Collection<E> collection = (Collection<E>) elements;
if (collection.isEmpty()) {
return ImmutableSet.of();
} else {
return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
}
} else {
Iterator<E> itr = elements.iterator();
if (itr.hasNext()) {
EnumSet<E> enumSet = EnumSet.of(itr.next());
Iterators.addAll(enumSet, itr);
return ImmutableEnumSet.asImmutable(enumSet);
} else {
return ImmutableSet.of();
}
}
}
/**
* Returns a new {@code EnumSet} instance containing the given elements.
* Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an
* exception on an empty collection, and it may be called on any iterable, not
* just a {@code Collection}.
*/
public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable,
Class<E> elementType) {
EnumSet<E> set = EnumSet.noneOf(elementType);
Iterables.addAll(set, iterable);
return set;
}
// HashSet
/**
* Creates a <i>mutable</i>, empty {@code HashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#noneOf} instead.
*
* @return a new, empty {@code HashSet}
*/
public static <E> HashSet<E> newHashSet() {
return new HashSet<E>();
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or
* {@link ImmutableSet#copyOf(Object[])} (for an array) instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link
* EnumSet#of(Enum, Enum[])} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSetWithExpectedSize(elements.length);
Collections.addAll(set, elements);
return set;
}
/**
* Creates a {@code HashSet} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code HashSet} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
return new HashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, use
* {@link #newEnumSet(Iterable, Class)} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? new HashSet<E>(Collections2.cast(elements))
: newHashSet(elements.iterator());
}
/**
* Creates a <i>mutable</i> {@code HashSet} instance containing the given
* elements in unspecified order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an
* {@link EnumSet} instead.
*
* @param elements the elements that the set should contain
* @return a new {@code HashSet} containing those elements (minus duplicates)
*/
public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
Iterators.addAll(set, elements);
return set;
}
/**
* Creates a thread-safe set backed by a hash map. The set is backed by a
* {@link ConcurrentHashMap} instance, and thus carries the same concurrency
* guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
* used as an element. The set is serializable.
*
* @return a new, empty thread-safe {@code Set}
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet() {
return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
/**
* Creates a thread-safe set backed by a hash map and containing the given
* elements. The set is backed by a {@link ConcurrentHashMap} instance, and
* thus carries the same concurrency guarantees.
*
* <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be
* used as an element. The set is serializable.
*
* @param elements the elements that the set should contain
* @return a new thread-safe set containing those elements (minus duplicates)
* @throws NullPointerException if {@code elements} or any of its contents is
* null
* @since 15.0
*/
public static <E> Set<E> newConcurrentHashSet(
Iterable<? extends E> elements) {
Set<E> set = newConcurrentHashSet();
Iterables.addAll(set, elements);
return set;
}
// LinkedHashSet
/**
* Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSet#of()} instead.
*
* @return a new, empty {@code LinkedHashSet}
*/
public static <E> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<E>();
}
/**
* Creates a {@code LinkedHashSet} instance, with a high enough "initial
* capacity" that it <i>should</i> hold {@code expectedSize} elements without
* growth. This behavior cannot be broadly guaranteed, but it is observed to
* be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned set.
*
* @param expectedSize the number of elements you expect to add to the
* returned set
* @return a new, empty {@code LinkedHashSet} with enough capacity to hold
* {@code expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 11.0
*/
public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(
int expectedSize) {
return new LinkedHashSet<E>(Maps.capacity(expectedSize));
}
/**
* Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the
* given elements in order.
*
* <p><b>Note:</b> if mutability is not required and the elements are
* non-null, use {@link ImmutableSet#copyOf(Iterable)} instead.
*
* @param elements the elements that the set should contain, in order
* @return a new {@code LinkedHashSet} containing those elements (minus
* duplicates)
*/
public static <E> LinkedHashSet<E> newLinkedHashSet(
Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<E>(Collections2.cast(elements));
}
LinkedHashSet<E> set = newLinkedHashSet();
Iterables.addAll(set, elements);
return set;
}
// TreeSet
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the
* natural sort ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#of()} instead.
*
* @return a new, empty {@code TreeSet}
*/
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<E>();
}
/**
* Creates a <i>mutable</i> {@code TreeSet} instance containing the given
* elements sorted by their natural ordering.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedSet#copyOf(Iterable)} instead.
*
* <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit
* comparator, this method has different behavior than
* {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with
* that comparator.
*
* @param elements the elements that the set should contain
* @return a new {@code TreeSet} containing those elements (minus duplicates)
*/
public static <E extends Comparable> TreeSet<E> newTreeSet(
Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
Iterables.addAll(set, elements);
return set;
}
/**
* Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedSet.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to use to sort the set
* @return a new, empty {@code TreeSet}
* @throws NullPointerException if {@code comparator} is null
*/
public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
return new TreeSet<E>(checkNotNull(comparator));
}
/**
* Creates an empty {@code Set} that uses identity to determine equality. It
* compares object references, instead of calling {@code equals}, to
* determine whether a provided object matches an element in the set. For
* example, {@code contains} returns {@code false} when passed an object that
* equals a set member, but isn't the same instance. This behavior is similar
* to the way {@code IdentityHashMap} handles key lookups.
*
* @since 8.0
*/
public static <E> Set<E> newIdentityHashSet() {
return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in
* the specified collection. If the collection is an {@link EnumSet}, this
* method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
* the specified collection must contain at least one element, in order to
* determine the element type. If the collection could be empty, use
* {@link #complementOf(Collection, Class)} instead of this method.
*
* @param collection the collection whose complement should be stored in the
* enum set
* @return a new, modifiable {@code EnumSet} containing all values of the enum
* that aren't present in the given collection
* @throws IllegalArgumentException if {@code collection} is not an
* {@code EnumSet} instance and contains no elements
*/
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection) {
if (collection instanceof EnumSet) {
return EnumSet.complementOf((EnumSet<E>) collection);
}
checkArgument(!collection.isEmpty(),
"collection is empty; use the other version of this method");
Class<E> type = collection.iterator().next().getDeclaringClass();
return makeComplementByHand(collection, type);
}
/**
* Creates an {@code EnumSet} consisting of all enum values that are not in
* the specified collection. This is equivalent to
* {@link EnumSet#complementOf}, but can act on any input collection, as long
* as the elements are of enum type.
*
* @param collection the collection whose complement should be stored in the
* {@code EnumSet}
* @param type the type of the elements in the set
* @return a new, modifiable {@code EnumSet} initially containing all the
* values of the enum not present in the given collection
*/
public static <E extends Enum<E>> EnumSet<E> complementOf(
Collection<E> collection, Class<E> type) {
checkNotNull(collection);
return (collection instanceof EnumSet)
? EnumSet.complementOf((EnumSet<E>) collection)
: makeComplementByHand(collection, type);
}
private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
Collection<E> collection, Class<E> type) {
EnumSet<E> result = EnumSet.allOf(type);
result.removeAll(collection);
return result;
}
/**
* Returns a set backed by the specified map. The resulting set displays
* the same ordering, concurrency, and performance characteristics as the
* backing map. In essence, this factory method provides a {@link Set}
* implementation corresponding to any {@link Map} implementation. There is no
* need to use this method on a {@link Map} implementation that already has a
* corresponding {@link Set} implementation (such as {@link java.util.HashMap}
* or {@link java.util.TreeMap}).
*
* <p>Each method invocation on the set returned by this method results in
* exactly one method invocation on the backing map or its {@code keySet}
* view, with one exception. The {@code addAll} method is implemented as a
* sequence of {@code put} invocations on the backing map.
*
* <p>The specified map must be empty at the time this method is invoked,
* and should not be accessed directly after this method returns. These
* conditions are ensured if the map is created empty, passed directly
* to this method, and no reference to the map is retained, as illustrated
* in the following code fragment: <pre> {@code
*
* Set<Object> identityHashSet = Sets.newSetFromMap(
* new IdentityHashMap<Object, Boolean>());}</pre>
*
* <p>This method has the same behavior as the JDK 6 method
* {@code Collections.newSetFromMap()}. The returned set is serializable if
* the backing map is.
*
* @param map the backing map
* @return the set backed by the map
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
return Platform.newSetFromMap(map);
}
/**
* An unmodifiable view of a set which may be backed by other sets; this view
* will change as the backing sets do. Contains methods to copy the data into
* a new set which will then remain stable. There is usually no reason to
* retain a reference of type {@code SetView}; typically, you either use it
* as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
* {@link #copyInto} and forget the {@code SetView} itself.
*
* @since 2.0 (imported from Google Collections Library)
*/
public abstract static class SetView<E> extends AbstractSet<E> {
private SetView() {} // no subclasses but our own
/**
* Returns an immutable copy of the current contents of this set view.
* Does not support null elements.
*
* <p><b>Warning:</b> this may have unexpected results if a backing set of
* this view uses a nonstandard notion of equivalence, for example if it is
* a {@link TreeSet} using a comparator that is inconsistent with {@link
* Object#equals(Object)}.
*/
public ImmutableSet<E> immutableCopy() {
return ImmutableSet.copyOf(this);
}
/**
* Copies the current contents of this set view into an existing set. This
* method has equivalent behavior to {@code set.addAll(this)}, assuming that
* all the sets involved are based on the same notion of equivalence.
*
* @return a reference to {@code set}, for convenience
*/
// Note: S should logically extend Set<? super E> but can't due to either
// some javac bug or some weirdness in the spec, not sure which.
public <S extends Set<E>> S copyInto(S set) {
set.addAll(this);
return set;
}
}
/**
* Returns an unmodifiable <b>view</b> of the union of two sets. The returned
* set contains all elements that are contained in either backing set.
* Iterating over the returned set iterates first over all the elements of
* {@code set1}, then over each element of {@code set2}, in order, that is not
* contained in {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based on
* different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
* the {@link Map#keySet} of an {@code IdentityHashMap} all are).
*
* <p><b>Note:</b> The returned view performs better when {@code set1} is the
* smaller of the two sets. If you have reason to believe one of your sets
* will generally be smaller than the other, pass it first.
*
* <p>Further, note that the current implementation is not suitable for nested
* {@code union} views, i.e. the following should be avoided when in a loop:
* {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
* set has a cubic complexity to the depth of the nesting.
*/
public static <E> SetView<E> union(
final Set<? extends E> set1, final Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Set<? extends E> set2minus1 = difference(set2, set1);
return new SetView<E>() {
@Override public int size() {
return set1.size() + set2minus1.size();
}
@Override public boolean isEmpty() {
return set1.isEmpty() && set2.isEmpty();
}
@Override public Iterator<E> iterator() {
return Iterators.unmodifiableIterator(
Iterators.concat(set1.iterator(), set2minus1.iterator()));
}
@Override public boolean contains(Object object) {
return set1.contains(object) || set2.contains(object);
}
@Override public <S extends Set<E>> S copyInto(S set) {
set.addAll(set1);
set.addAll(set2);
return set;
}
@Override public ImmutableSet<E> immutableCopy() {
return new ImmutableSet.Builder<E>()
.addAll(set1).addAll(set2).build();
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the intersection of two sets. The
* returned set contains all elements that are contained by both backing sets.
* The iteration order of the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* <p><b>Note:</b> The returned view performs slightly better when {@code
* set1} is the smaller of the two sets. If you have reason to believe one of
* your sets will generally be smaller than the other, pass it first.
* Unfortunately, since this method sets the generic type of the returned set
* based on the type of the first set passed, this could in rare cases force
* you to make a cast, for example: <pre> {@code
*
* Set<Object> aFewBadObjects = ...
* Set<String> manyBadStrings = ...
*
* // impossible for a non-String to be in the intersection
* SuppressWarnings("unchecked")
* Set<String> badStrings = (Set) Sets.intersection(
* aFewBadObjects, manyBadStrings);}</pre>
*
* <p>This is unfortunate, but should come up only very rarely.
*/
public static <E> SetView<E> intersection(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> inSet2 = Predicates.in(set2);
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), inSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return !iterator().hasNext();
}
@Override public boolean contains(Object object) {
return set1.contains(object) && set2.contains(object);
}
@Override public boolean containsAll(Collection<?> collection) {
return set1.containsAll(collection)
&& set2.containsAll(collection);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the difference of two sets. The
* returned set contains all elements that are contained by {@code set1} and
* not contained by {@code set2}. {@code set2} may also contain elements not
* present in {@code set1}; these are simply ignored. The iteration order of
* the returned set matches that of {@code set1}.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*/
public static <E> SetView<E> difference(
final Set<E> set1, final Set<?> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
return new SetView<E>() {
@Override public Iterator<E> iterator() {
return Iterators.filter(set1.iterator(), notInSet2);
}
@Override public int size() {
return Iterators.size(iterator());
}
@Override public boolean isEmpty() {
return set2.containsAll(set1);
}
@Override public boolean contains(Object element) {
return set1.contains(element) && !set2.contains(element);
}
};
}
/**
* Returns an unmodifiable <b>view</b> of the symmetric difference of two
* sets. The returned set contains all elements that are contained in either
* {@code set1} or {@code set2} but not in both. The iteration order of the
* returned set is undefined.
*
* <p>Results are undefined if {@code set1} and {@code set2} are sets based
* on different equivalence relations (as {@code HashSet}, {@code TreeSet},
* and the keySet of an {@code IdentityHashMap} all are).
*
* @since 3.0
*/
public static <E> SetView<E> symmetricDifference(
Set<? extends E> set1, Set<? extends E> set2) {
checkNotNull(set1, "set1");
checkNotNull(set2, "set2");
// TODO(kevinb): Replace this with a more efficient implementation
return difference(union(set1, set2), intersection(set1, set2));
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate. The
* returned set is a live view of {@code unfiltered}; changes to one affect
* the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set's {@code add()} and {@code addAll()} methods throw
* an {@link IllegalArgumentException}. When methods such as {@code
* removeAll()} and {@code clear()} are called on the filtered set, only
* elements that satisfy the filter will be removed from the underlying set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate
* across every element in the underlying set and determine which elements
* satisfy the filter. When a live view is <i>not</i> needed, it may be faster
* to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*/
// TODO(kevinb): how to omit that last sentence when building GWT javadoc?
public static <E> Set<E> filter(
Set<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof SortedSet) {
return filter((SortedSet<E>) unfiltered, predicate);
}
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSet<E>(
(Set<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSet<E> extends FilteredCollection<E>
implements Set<E> {
FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override public boolean equals(@Nullable Object object) {
return equalsImpl(this, object);
}
@Override public int hashCode() {
return hashCodeImpl(this);
}
}
/**
* Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
* satisfy a predicate. The returned set is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting set's iterator does not support {@code remove()}, but all
* other set methods are supported. When given an element that doesn't satisfy
* the predicate, the set's {@code add()} and {@code addAll()} methods throw
* an {@link IllegalArgumentException}. When methods such as
* {@code removeAll()} and {@code clear()} are called on the filtered set,
* only elements that satisfy the filter will be removed from the underlying
* set.
*
* <p>The returned set isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered set's methods, such as {@code size()}, iterate across
* every element in the underlying set and determine which elements satisfy
* the filter. When a live view is <i>not</i> needed, it may be faster to copy
* {@code Iterables.filter(unfiltered, predicate)} and use the copy.
*
* <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such as
* {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
* equals. (See {@link Iterables#filter(Iterable, Class)} for related
* functionality.)
*
* @since 11.0
*/
public static <E> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
return Platform.setsFilterSortedSet(unfiltered, predicate);
}
static <E> SortedSet<E> filterSortedIgnoreNavigable(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
if (unfiltered instanceof FilteredSet) {
// Support clear(), removeAll(), and retainAll() when filtering a filtered
// collection.
FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
Predicate<E> combinedPredicate
= Predicates.<E>and(filtered.predicate, predicate);
return new FilteredSortedSet<E>(
(SortedSet<E>) filtered.unfiltered, combinedPredicate);
}
return new FilteredSortedSet<E>(
checkNotNull(unfiltered), checkNotNull(predicate));
}
private static class FilteredSortedSet<E> extends FilteredSet<E>
implements SortedSet<E> {
FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
super(unfiltered, predicate);
}
@Override
public Comparator<? super E> comparator() {
return ((SortedSet<E>) unfiltered).comparator();
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement),
predicate);
}
@Override
public SortedSet<E> headSet(E toElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
}
@Override
public E first() {
return iterator().next();
}
@Override
public E last() {
SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
while (true) {
E element = sortedUnfiltered.last();
if (predicate.apply(element)) {
return element;
}
sortedUnfiltered = sortedUnfiltered.headSet(element);
}
}
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(ImmutableList.of(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C")))}</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be
* empty. If no sets at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
List<? extends Set<? extends B>> sets) {
return CartesianSet.create(sets);
}
/**
* Returns every possible list that can be formed by choosing one element
* from each of the given sets in order; the "n-ary
* <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
* product</a>" of the sets. For example: <pre> {@code
*
* Sets.cartesianProduct(
* ImmutableSet.of(1, 2),
* ImmutableSet.of("A", "B", "C"))}</pre>
*
* <p>returns a set containing six lists:
*
* <ul>
* <li>{@code ImmutableList.of(1, "A")}
* <li>{@code ImmutableList.of(1, "B")}
* <li>{@code ImmutableList.of(1, "C")}
* <li>{@code ImmutableList.of(2, "A")}
* <li>{@code ImmutableList.of(2, "B")}
* <li>{@code ImmutableList.of(2, "C")}
* </ul>
*
* <p>The result is guaranteed to be in the "traditional", lexicographical
* order for Cartesian products that you would get from nesting for loops:
* <pre> {@code
*
* for (B b0 : sets.get(0)) {
* for (B b1 : sets.get(1)) {
* ...
* ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
* // operate on tuple
* }
* }}</pre>
*
* <p>Note that if any input set is empty, the Cartesian product will also be
* empty. If no sets at all are provided (an empty list), the resulting
* Cartesian product has one element, an empty list (counter-intuitive, but
* mathematically consistent).
*
* <p><i>Performance notes:</i> while the cartesian product of sets of size
* {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
* consumption is much smaller. When the cartesian set is constructed, the
* input sets are merely copied. Only as the resulting set is iterated are the
* individual lists created, and these are not retained after iteration.
*
* @param sets the sets to choose elements from, in the order that
* the elements chosen from those sets should appear in the resulting
* lists
* @param <B> any common base class shared by all axes (often just {@link
* Object})
* @return the Cartesian product, as an immutable set containing immutable
* lists
* @throws NullPointerException if {@code sets}, any one of the {@code sets},
* or any element of a provided set is null
* @since 2.0
*/
public static <B> Set<List<B>> cartesianProduct(
Set<? extends B>... sets) {
return cartesianProduct(Arrays.asList(sets));
}
private static final class CartesianSet<E>
extends ForwardingCollection<List<E>> implements Set<List<E>> {
private transient final ImmutableList<ImmutableSet<E>> axes;
private transient final CartesianList<E> delegate;
static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
for (Set<? extends E> set : sets) {
ImmutableSet<E> copy = ImmutableSet.copyOf(set);
if (copy.isEmpty()) {
return ImmutableSet.of();
}
axesBuilder.add(copy);
}
final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() {
@Override
public int size() {
return axes.size();
}
@Override
public List<E> get(int index) {
return axes.get(index).asList();
}
@Override
boolean isPartialView() {
return true;
}
};
return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
}
private CartesianSet(
ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
this.axes = axes;
this.delegate = delegate;
}
@Override
protected Collection<List<E>> delegate() {
return delegate;
}
@Override public boolean equals(@Nullable Object object) {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
if (object instanceof CartesianSet) {
CartesianSet<?> that = (CartesianSet<?>) object;
return this.axes.equals(that.axes);
}
return super.equals(object);
}
@Override
public int hashCode() {
// Warning: this is broken if size() == 0, so it is critical that we
// substitute an empty ImmutableSet to the user in place of this
// It's a weird formula, but tests prove it works.
int adjust = size() - 1;
for (int i = 0; i < axes.size(); i++) {
adjust *= 31;
adjust = ~~adjust;
// in GWT, we have to deal with integer overflow carefully
}
int hash = 1;
for (Set<E> axis : axes) {
hash = 31 * hash + (size() / axis.size() * axis.hashCode());
hash = ~~hash;
}
hash += adjust;
return ~~hash;
}
}
/**
* Returns the set of all possible subsets of {@code set}. For example,
* {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
* {1}, {2}, {1, 2}}}.
*
* <p>Elements appear in these subsets in the same iteration order as they
* appeared in the input set. The order in which these subsets appear in the
* outer set is undefined. Note that the power set of the empty set is not the
* empty set, but a one-element set containing the empty set.
*
* <p>The returned set and its constituent sets use {@code equals} to decide
* whether two elements are identical, even if the input set uses a different
* concept of equivalence.
*
* <p><i>Performance notes:</i> while the power set of a set with size {@code
* n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
* power set is constructed, the input set is merely copied. Only as the
* power set is iterated are the individual subsets created, and these subsets
* themselves occupy only a small constant amount of memory.
*
* @param set the set of elements to construct a power set from
* @return the power set, as an immutable set of immutable sets
* @throws IllegalArgumentException if {@code set} has more than 30 unique
* elements (causing the power set size to exceed the {@code int} range)
* @throws NullPointerException if {@code set} is or contains {@code null}
* @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at
* Wikipedia</a>
* @since 4.0
*/
@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) {
return new PowerSet<E>(set);
}
private static final class SubSet<E> extends AbstractSet<E> {
private final ImmutableMap<E, Integer> inputSet;
private final int mask;
SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
this.inputSet = inputSet;
this.mask = mask;
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableIterator<E>() {
final ImmutableList<E> elements = inputSet.keySet().asList();
int remainingSetBits = mask;
@Override
public boolean hasNext() {
return remainingSetBits != 0;
}
@Override
public E next() {
int index = Integer.numberOfTrailingZeros(remainingSetBits);
if (index == 32) {
throw new NoSuchElementException();
}
remainingSetBits &= ~(1 << index);
return elements.get(index);
}
};
}
@Override
public int size() {
return Integer.bitCount(mask);
}
@Override
public boolean contains(@Nullable Object o) {
Integer index = inputSet.get(o);
return index != null && (mask & (1 << index)) != 0;
}
}
private static final class PowerSet<E> extends AbstractSet<Set<E>> {
final ImmutableMap<E, Integer> inputSet;
PowerSet(Set<E> input) {
ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
int i = 0;
for (E e : checkNotNull(input)) {
builder.put(e, i++);
}
this.inputSet = builder.build();
checkArgument(inputSet.size() <= 30,
"Too many elements to create power set: %s > 30", inputSet.size());
}
@Override public int size() {
return 1 << inputSet.size();
}
@Override public boolean isEmpty() {
return false;
}
@Override public Iterator<Set<E>> iterator() {
return new AbstractIndexedListIterator<Set<E>>(size()) {
@Override protected Set<E> get(final int setBits) {
return new SubSet<E>(inputSet, setBits);
}
};
}
@Override public boolean contains(@Nullable Object obj) {
if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
return inputSet.keySet().containsAll(set);
}
return false;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof PowerSet) {
PowerSet<?> that = (PowerSet<?>) obj;
return inputSet.equals(that.inputSet);
}
return super.equals(obj);
}
@Override public int hashCode() {
/*
* The sum of the sums of the hash codes in each subset is just the sum of
* each input element's hash code times the number of sets that element
* appears in. Each element appears in exactly half of the 2^n sets, so:
*/
return inputSet.keySet().hashCode() << (inputSet.size() - 1);
}
@Override public String toString() {
return "powerSet(" + inputSet + ")";
}
}
/**
* An implementation for {@link Set#hashCode()}.
*/
static int hashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
hashCode = ~~hashCode;
// Needed to deal with unusual integer overflow in GWT.
}
return hashCode;
}
/**
* An implementation for {@link Set#equals(Object)}.
*/
static boolean equalsImpl(Set<?> s, @Nullable Object object) {
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException ignored) {
return false;
} catch (ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* Remove each element in an iterable from a set.
*/
static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
boolean changed = false;
while (iterator.hasNext()) {
changed |= set.remove(iterator.next());
}
return changed;
}
static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
checkNotNull(collection); // for GWT
if (collection instanceof Multiset) {
collection = ((Multiset<?>) collection).elementSet();
}
/*
* AbstractSet.removeAll(List) has quadratic behavior if the list size
* is just less than the set's size. We augment the test by
* assuming that sets have fast contains() performance, and other
* collections don't. See
* http://code.google.com/p/guava-libraries/issues/detail?id=1013
*/
if (collection instanceof Set && collection.size() > set.size()) {
return Iterators.removeAll(set.iterator(), collection);
} else {
return removeAllImpl(set, collection.iterator());
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.EntryTransformer;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Minimal GWT emulation of {@code com.google.common.collect.Platform}.
*
* <p><strong>This .java file should never be consumed by javac.</strong>
*
* @author Hayward Chan
*/
class Platform {
static <T> T[] newArray(T[] reference, int length) {
return GwtPlatform.newArray(reference, length);
}
/*
* Regarding newSetForMap() and SetFromMap:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
return new SetFromMap<E>(map);
}
private static class SetFromMap<E> extends AbstractSet<E>
implements Set<E>, Serializable {
private final Map<E, Boolean> m; // The backing map
private transient Set<E> s; // Its keySet
SetFromMap(Map<E, Boolean> map) {
checkArgument(map.isEmpty(), "Map is non-empty");
m = map;
s = map.keySet();
}
@Override public void clear() {
m.clear();
}
@Override public int size() {
return m.size();
}
@Override public boolean isEmpty() {
return m.isEmpty();
}
@Override public boolean contains(Object o) {
return m.containsKey(o);
}
@Override public boolean remove(Object o) {
return m.remove(o) != null;
}
@Override public boolean add(E e) {
return m.put(e, Boolean.TRUE) == null;
}
@Override public Iterator<E> iterator() {
return s.iterator();
}
@Override public Object[] toArray() {
return s.toArray();
}
@Override public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
@Override public String toString() {
return s.toString();
}
@Override public int hashCode() {
return s.hashCode();
}
@Override public boolean equals(@Nullable Object object) {
return this == object || this.s.equals(object);
}
@Override public boolean containsAll(Collection<?> c) {
return s.containsAll(c);
}
@Override public boolean removeAll(Collection<?> c) {
return s.removeAll(c);
}
@Override public boolean retainAll(Collection<?> c) {
return s.retainAll(c);
}
}
static MapMaker tryWeakKeys(MapMaker mapMaker) {
return mapMaker;
}
static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return Maps.transformEntriesIgnoreNavigable(fromMap, transformer);
}
static <K, V> SortedMap<K, V> mapsAsMapSortedSet(
SortedSet<K> set, Function<? super K, V> function) {
return Maps.asMapSortedIgnoreNavigable(set, function);
}
static <E> SortedSet<E> setsFilterSortedSet(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
return Sets.filterSortedIgnoreNavigable(unfiltered, predicate);
}
static <K, V> SortedMap<K, V> mapsFilterSortedMap(
SortedMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> predicate) {
return Maps.filterSortedIgnoreNavigable(unfiltered, predicate);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* {@code entrySet()} implementation for {@link ImmutableMap}.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
ImmutableMapEntrySet() {}
abstract ImmutableMap<K, V> map();
@Override
public int size() {
return map().size();
}
@Override
public boolean contains(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
V value = map().get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
return false;
}
@Override
boolean isPartialView() {
return map().isPartialView();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.annotation.Nullable;
/**
* Implementation of {@code Multimap} whose keys and values are ordered by
* their natural ordering or by supplied comparators. In all cases, this
* implementation uses {@link Comparable#compareTo} or {@link
* Comparator#compare} instead of {@link Object#equals} to determine
* equivalence of instances.
*
* <p><b>Warning:</b> The comparators or comparables used must be <i>consistent
* with equals</i> as explained by the {@link Comparable} class specification.
* Otherwise, the resulting multiset will violate the general contract of {@link
* SetMultimap}, which it is specified in terms of {@link Object#equals}.
*
* <p>The collections returned by {@code keySet} and {@code asMap} iterate
* through the keys according to the key comparator ordering or the natural
* ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code
* replaceValues} return collections that iterate through the values according
* to the value comparator ordering or the natural ordering of the values. The
* collections generated by {@code entries}, {@code keys}, and {@code values}
* iterate across the keys according to the above key ordering, and for each
* key they iterate across the values according to the value ordering.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new
* key-value pair equal to an existing key-value pair has no effect.
*
* <p>Null keys and values are permitted (provided, of course, that the
* respective comparators support them). All optional multimap methods are
* supported, and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedSortedSetMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> {
private transient Comparator<? super K> keyComparator;
private transient Comparator<? super V> valueComparator;
/**
* Creates an empty {@code TreeMultimap} ordered by the natural ordering of
* its keys and values.
*/
public static <K extends Comparable, V extends Comparable>
TreeMultimap<K, V> create() {
return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural());
}
/**
* Creates an empty {@code TreeMultimap} instance using explicit comparators.
* Neither comparator may be null; use {@link Ordering#natural()} to specify
* natural order.
*
* @param keyComparator the comparator that determines the key ordering
* @param valueComparator the comparator that determines the value ordering
*/
public static <K, V> TreeMultimap<K, V> create(
Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator) {
return new TreeMultimap<K, V>(checkNotNull(keyComparator),
checkNotNull(valueComparator));
}
/**
* Constructs a {@code TreeMultimap}, ordered by the natural ordering of its
* keys and values, with the same mappings as the specified multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K extends Comparable, V extends Comparable>
TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(),
multimap);
}
TreeMultimap(Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator) {
super(new TreeMap<K, Collection<V>>(keyComparator));
this.keyComparator = keyComparator;
this.valueComparator = valueComparator;
}
private TreeMultimap(Comparator<? super K> keyComparator,
Comparator<? super V> valueComparator,
Multimap<? extends K, ? extends V> multimap) {
this(keyComparator, valueComparator);
putAll(multimap);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code TreeSet} for a collection of values for one key.
*
* @return a new {@code TreeSet} containing a collection of values for one
* key
*/
@Override SortedSet<V> createCollection() {
return new TreeSet<V>(valueComparator);
}
@Override
Collection<V> createCollection(@Nullable K key) {
if (key == null) {
keyComparator().compare(key, key);
}
return super.createCollection(key);
}
/**
* Returns the comparator that orders the multimap keys.
*/
public Comparator<? super K> keyComparator() {
return keyComparator;
}
@Override
public Comparator<? super V> valueComparator() {
return valueComparator;
}
/*
* The following @GwtIncompatible methods override the methods in
* AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM implementations,
* which return SortedSets and SortedMaps.
*/
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
/**
* A skeleton implementation of a descending multiset. Only needs
* {@code forwardMultiset()} and {@code entryIterator()}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
abstract class DescendingMultiset<E> extends ForwardingMultiset<E>
implements SortedMultiset<E> {
abstract SortedMultiset<E> forwardMultiset();
private transient Comparator<? super E> comparator;
@Override public Comparator<? super E> comparator() {
Comparator<? super E> result = comparator;
if (result == null) {
return comparator =
Ordering.from(forwardMultiset().comparator()).<E>reverse();
}
return result;
}
private transient SortedSet<E> elementSet;
@Override public SortedSet<E> elementSet() {
SortedSet<E> result = elementSet;
if (result == null) {
return elementSet = new SortedMultisets.ElementSet<E>(this);
}
return result;
}
@Override public Entry<E> pollFirstEntry() {
return forwardMultiset().pollLastEntry();
}
@Override public Entry<E> pollLastEntry() {
return forwardMultiset().pollFirstEntry();
}
@Override public SortedMultiset<E> headMultiset(E toElement,
BoundType boundType) {
return forwardMultiset().tailMultiset(toElement, boundType)
.descendingMultiset();
}
@Override public SortedMultiset<E> subMultiset(E fromElement,
BoundType fromBoundType, E toElement, BoundType toBoundType) {
return forwardMultiset().subMultiset(toElement, toBoundType, fromElement,
fromBoundType).descendingMultiset();
}
@Override public SortedMultiset<E> tailMultiset(E fromElement,
BoundType boundType) {
return forwardMultiset().headMultiset(fromElement, boundType)
.descendingMultiset();
}
@Override protected Multiset<E> delegate() {
return forwardMultiset();
}
@Override public SortedMultiset<E> descendingMultiset() {
return forwardMultiset();
}
@Override public Entry<E> firstEntry() {
return forwardMultiset().lastEntry();
}
@Override public Entry<E> lastEntry() {
return forwardMultiset().firstEntry();
}
abstract Iterator<Entry<E>> entryIterator();
private transient Set<Entry<E>> entrySet;
@Override public Set<Entry<E>> entrySet() {
Set<Entry<E>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
Set<Entry<E>> createEntrySet() {
return new Multisets.EntrySet<E>() {
@Override Multiset<E> multiset() {
return DescendingMultiset.this;
}
@Override public Iterator<Entry<E>> iterator() {
return entryIterator();
}
@Override public int size() {
return forwardMultiset().entrySet().size();
}
};
}
@Override public Iterator<E> iterator() {
return Multisets.iteratorImpl(this);
}
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override public String toString() {
return entrySet().toString();
}
} | Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.unmodifiableList;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractSequentialList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An implementation of {@code ListMultimap} that supports deterministic
* iteration order for both keys and values. The iteration order is preserved
* across non-distinct key values. For example, for the following multimap
* definition: <pre> {@code
*
* Multimap<K, V> multimap = LinkedListMultimap.create();
* multimap.put(key1, foo);
* multimap.put(key2, bar);
* multimap.put(key1, baz);}</pre>
*
* ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]},
* and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the
* iteration order is kept consistent between keys, entries and values. For
* example, calling: <pre> {@code
*
* map.remove(key1, foo);}</pre>
*
* <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the
* key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator
* returns mutable map entries, and {@link #replaceValues} attempts to preserve
* iteration order as much as possible.
*
* <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate
* through the keys in the order they were first added to the multimap.
* Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues}
* return collections that iterate through the values in the order they were
* added. The collections generated by {@link #entries()}, {@link #keys()}, and
* {@link #values} iterate across the key-value mappings in the order they were
* added to the multimap.
*
* <p>The {@link #values()} and {@link #entries()} methods both return a
* {@code List}, instead of the {@code Collection} specified by the {@link
* ListMultimap} interface.
*
* <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()},
* {@link #values}, {@link #entries()}, and {@link #asMap} return collections
* that are views of the multimap. If the multimap is modified while an
* iteration over any of those collections is in progress, except through the
* iterator's methods, the results of the iteration are undefined.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedListMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class LinkedListMultimap<K, V> extends AbstractMultimap<K, V>
implements ListMultimap<K, V>, Serializable {
/*
* Order is maintained using a linked list containing all key-value pairs. In
* addition, a series of disjoint linked lists of "siblings", each containing
* the values for a specific key, is used to implement {@link
* ValueForKeyIterator} in constant time.
*/
private static final class Node<K, V> extends AbstractMapEntry<K, V> {
final K key;
V value;
Node<K, V> next; // the next node (with any key)
Node<K, V> previous; // the previous node (with any key)
Node<K, V> nextSibling; // the next node with the same key
Node<K, V> previousSibling; // the previous node with the same key
Node(@Nullable K key, @Nullable V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(@Nullable V newValue) {
V result = value;
this.value = newValue;
return result;
}
}
private static class KeyList<K, V> {
Node<K, V> head;
Node<K, V> tail;
int count;
KeyList(Node<K, V> firstNode) {
this.head = firstNode;
this.tail = firstNode;
firstNode.previousSibling = null;
firstNode.nextSibling = null;
this.count = 1;
}
}
private transient Node<K, V> head; // the head for all keys
private transient Node<K, V> tail; // the tail for all keys
private transient Map<K, KeyList<K, V>> keyToKeyList;
private transient int size;
/*
* Tracks modifications to keyToKeyList so that addition or removal of keys invalidates
* preexisting iterators. This does *not* track simple additions and removals of values
* that are not the first to be added or last to be removed for their key.
*/
private transient int modCount;
/**
* Creates a new, empty {@code LinkedListMultimap} with the default initial
* capacity.
*/
public static <K, V> LinkedListMultimap<K, V> create() {
return new LinkedListMultimap<K, V>();
}
/**
* Constructs an empty {@code LinkedListMultimap} with enough capacity to hold
* the specified number of keys without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @throws IllegalArgumentException if {@code expectedKeys} is negative
*/
public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) {
return new LinkedListMultimap<K, V>(expectedKeys);
}
/**
* Constructs a {@code LinkedListMultimap} with the same mappings as the
* specified {@code Multimap}. The new multimap has the same
* {@link Multimap#entries()} iteration order as the input multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> LinkedListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new LinkedListMultimap<K, V>(multimap);
}
LinkedListMultimap() {
keyToKeyList = Maps.newHashMap();
}
private LinkedListMultimap(int expectedKeys) {
keyToKeyList = new HashMap<K, KeyList<K, V>>(expectedKeys);
}
private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size());
putAll(multimap);
}
/**
* Adds a new node for the specified key-value pair before the specified
* {@code nextSibling} element, or at the end of the list if {@code
* nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be
* for an node for the same {@code key}!
*/
private Node<K, V> addNode(
@Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) {
Node<K, V> node = new Node<K, V>(key, value);
if (head == null) { // empty list
head = tail = node;
keyToKeyList.put(key, new KeyList<K, V>(node));
modCount++;
} else if (nextSibling == null) { // non-empty list, add to tail
tail.next = node;
node.previous = tail;
tail = node;
KeyList<K, V> keyList = keyToKeyList.get(key);
if (keyList == null) {
keyToKeyList.put(key, keyList = new KeyList<K, V>(node));
modCount++;
} else {
keyList.count++;
Node<K, V> keyTail = keyList.tail;
keyTail.nextSibling = node;
node.previousSibling = keyTail;
keyList.tail = node;
}
} else { // non-empty list, insert before nextSibling
KeyList<K, V> keyList = keyToKeyList.get(key);
keyList.count++;
node.previous = nextSibling.previous;
node.previousSibling = nextSibling.previousSibling;
node.next = nextSibling;
node.nextSibling = nextSibling;
if (nextSibling.previousSibling == null) { // nextSibling was key head
keyToKeyList.get(key).head = node;
} else {
nextSibling.previousSibling.nextSibling = node;
}
if (nextSibling.previous == null) { // nextSibling was head
head = node;
} else {
nextSibling.previous.next = node;
}
nextSibling.previous = node;
nextSibling.previousSibling = node;
}
size++;
return node;
}
/**
* Removes the specified node from the linked list. This method is only
* intended to be used from the {@code Iterator} classes. See also {@link
* LinkedListMultimap#removeAllNodes(Object)}.
*/
private void removeNode(Node<K, V> node) {
if (node.previous != null) {
node.previous.next = node.next;
} else { // node was head
head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
} else { // node was tail
tail = node.previous;
}
if (node.previousSibling == null && node.nextSibling == null) {
KeyList<K, V> keyList = keyToKeyList.remove(node.key);
keyList.count = 0;
modCount++;
} else {
KeyList<K, V> keyList = keyToKeyList.get(node.key);
keyList.count--;
if (node.previousSibling == null) {
keyList.head = node.nextSibling;
} else {
node.previousSibling.nextSibling = node.nextSibling;
}
if (node.nextSibling == null) {
keyList.tail = node.previousSibling;
} else {
node.nextSibling.previousSibling = node.previousSibling;
}
}
size--;
}
/** Removes all nodes for the specified key. */
private void removeAllNodes(@Nullable Object key) {
Iterators.clear(new ValueForKeyIterator(key));
}
/** Helper method for verifying that an iterator element is present. */
private static void checkElement(@Nullable Object node) {
if (node == null) {
throw new NoSuchElementException();
}
}
/** An {@code Iterator} over all nodes. */
private class NodeIterator implements ListIterator<Entry<K, V>> {
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
int expectedModCount = modCount;
NodeIterator(int index) {
int size = size();
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = head;
while (index-- > 0) {
next();
}
}
current = null;
}
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@Override
public Node<K, V> next() {
checkForConcurrentModification();
checkElement(next);
previous = current = next;
next = next.next;
nextIndex++;
return current;
}
@Override
public void remove() {
checkForConcurrentModification();
checkState(current != null);
if (current != next) { // after call to next()
previous = current.previous;
nextIndex--;
} else { // after call to previous()
next = current.next;
}
removeNode(current);
current = null;
expectedModCount = modCount;
}
@Override
public boolean hasPrevious() {
checkForConcurrentModification();
return previous != null;
}
@Override
public Node<K, V> previous() {
checkForConcurrentModification();
checkElement(previous);
next = current = previous;
previous = previous.previous;
nextIndex--;
return current;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void set(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
@Override
public void add(Entry<K, V> e) {
throw new UnsupportedOperationException();
}
void setValue(V value) {
checkState(current != null);
current.value = value;
}
}
/** An {@code Iterator} over distinct keys in key head order. */
private class DistinctKeyIterator implements Iterator<K> {
final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size());
Node<K, V> next = head;
Node<K, V> current;
int expectedModCount = modCount;
private void checkForConcurrentModification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForConcurrentModification();
return next != null;
}
@Override
public K next() {
checkForConcurrentModification();
checkElement(next);
current = next;
seenKeys.add(current.key);
do { // skip ahead to next unseen key
next = next.next;
} while ((next != null) && !seenKeys.add(next.key));
return current.key;
}
@Override
public void remove() {
checkForConcurrentModification();
checkState(current != null);
removeAllNodes(current.key);
current = null;
expectedModCount = modCount;
}
}
/** A {@code ListIterator} over values for a specified key. */
private class ValueForKeyIterator implements ListIterator<V> {
final Object key;
int nextIndex;
Node<K, V> next;
Node<K, V> current;
Node<K, V> previous;
/** Constructs a new iterator over all values for the specified key. */
ValueForKeyIterator(@Nullable Object key) {
this.key = key;
KeyList<K, V> keyList = keyToKeyList.get(key);
next = (keyList == null) ? null : keyList.head;
}
/**
* Constructs a new iterator over all values for the specified key starting
* at the specified index. This constructor is optimized so that it starts
* at either the head or the tail, depending on which is closer to the
* specified index. This allows adds to the tail to be done in constant
* time.
*
* @throws IndexOutOfBoundsException if index is invalid
*/
public ValueForKeyIterator(@Nullable Object key, int index) {
KeyList<K, V> keyList = keyToKeyList.get(key);
int size = (keyList == null) ? 0 : keyList.count;
checkPositionIndex(index, size);
if (index >= (size / 2)) {
previous = (keyList == null) ? null : keyList.tail;
nextIndex = size;
while (index++ < size) {
previous();
}
} else {
next = (keyList == null) ? null : keyList.head;
while (index-- > 0) {
next();
}
}
this.key = key;
current = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public V next() {
checkElement(next);
previous = current = next;
next = next.nextSibling;
nextIndex++;
return current.value;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public V previous() {
checkElement(previous);
next = current = previous;
previous = previous.previousSibling;
nextIndex--;
return current.value;
}
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
@Override
public void remove() {
checkState(current != null);
if (current != next) { // after call to next()
previous = current.previousSibling;
nextIndex--;
} else { // after call to previous()
next = current.nextSibling;
}
removeNode(current);
current = null;
}
@Override
public void set(V value) {
checkState(current != null);
current.value = value;
}
@Override
@SuppressWarnings("unchecked")
public void add(V value) {
previous = addNode((K) key, value, next);
nextIndex++;
current = null;
}
}
// Query Operations
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return keyToKeyList.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
// Modification Operations
/**
* Stores a key-value pair in the multimap.
*
* @param key key to store in the multimap
* @param value value to store in the multimap
* @return {@code true} always
*/
@Override
public boolean put(@Nullable K key, @Nullable V value) {
addNode(key, value, null);
return true;
}
// Bulk Operations
/**
* {@inheritDoc}
*
* <p>If any entries for the specified {@code key} already exist in the
* multimap, their values are changed in-place without affecting the iteration
* order.
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
List<V> oldValues = getCopy(key);
ListIterator<V> keyValues = new ValueForKeyIterator(key);
Iterator<? extends V> newValues = values.iterator();
// Replace existing values, if any.
while (keyValues.hasNext() && newValues.hasNext()) {
keyValues.next();
keyValues.set(newValues.next());
}
// Remove remaining old values, if any.
while (keyValues.hasNext()) {
keyValues.next();
keyValues.remove();
}
// Add remaining new values, if any.
while (newValues.hasNext()) {
keyValues.add(newValues.next());
}
return oldValues;
}
private List<V> getCopy(@Nullable Object key) {
return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key)));
}
/**
* {@inheritDoc}
*
* <p>The returned list is immutable and implements
* {@link java.util.RandomAccess}.
*/
@Override
public List<V> removeAll(@Nullable Object key) {
List<V> oldValues = getCopy(key);
removeAllNodes(key);
return oldValues;
}
@Override
public void clear() {
head = null;
tail = null;
keyToKeyList.clear();
size = 0;
modCount++;
}
// Views
/**
* {@inheritDoc}
*
* <p>If the multimap is modified while an iteration over the list is in
* progress (except through the iterator's own {@code add}, {@code set} or
* {@code remove} operations) the results of the iteration are undefined.
*
* <p>The returned list is not serializable and does not have random access.
*/
@Override
public List<V> get(final @Nullable K key) {
return new AbstractSequentialList<V>() {
@Override public int size() {
KeyList<K, V> keyList = keyToKeyList.get(key);
return (keyList == null) ? 0 : keyList.count;
}
@Override public ListIterator<V> listIterator(int index) {
return new ValueForKeyIterator(key, index);
}
};
}
@Override
Set<K> createKeySet() {
return new Sets.ImprovedAbstractSet<K>() {
@Override public int size() {
return keyToKeyList.size();
}
@Override public Iterator<K> iterator() {
return new DistinctKeyIterator();
}
@Override public boolean contains(Object key) { // for performance
return containsKey(key);
}
@Override
public boolean remove(Object o) { // for performance
return !LinkedListMultimap.this.removeAll(o).isEmpty();
}
};
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the values
* in the order they were added to the multimap. Because the values may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*/
@Override
public List<V> values() {
return (List<V>) super.values();
}
@Override
List<V> createValues() {
return new AbstractSequentialList<V>() {
@Override public int size() {
return size;
}
@Override public ListIterator<V> listIterator(int index) {
final NodeIterator nodeItr = new NodeIterator(index);
return new TransformedListIterator<Entry<K, V>, V>(nodeItr) {
@Override
V transform(Entry<K, V> entry) {
return entry.getValue();
}
@Override
public void set(V value) {
nodeItr.setValue(value);
}
};
}
};
}
/**
* {@inheritDoc}
*
* <p>The iterator generated by the returned collection traverses the entries
* in the order they were added to the multimap. Because the entries may have
* duplicates and follow the insertion ordering, this method returns a {@link
* List}, instead of the {@link Collection} specified in the {@link
* ListMultimap} interface.
*
* <p>An entry's {@link Entry#getKey} method always returns the same key,
* regardless of what happens subsequently. As long as the corresponding
* key-value mapping is not removed from the multimap, {@link Entry#getValue}
* returns the value from the multimap, which may change over time, and {@link
* Entry#setValue} modifies that value. Removing the mapping from the
* multimap does not alter the value returned by {@code getValue()}, though a
* subsequent {@code setValue()} call won't update the multimap but will lead
* to a revised value being returned by {@code getValue()}.
*/
@Override
public List<Entry<K, V>> entries() {
return (List<Entry<K, V>>) super.entries();
}
@Override
List<Entry<K, V>> createEntries() {
return new AbstractSequentialList<Entry<K, V>>() {
@Override public int size() {
return size;
}
@Override public ListIterator<Entry<K, V>> listIterator(int index) {
return new NodeIterator(index);
}
};
}
@Override
Iterator<Entry<K, V>> entryIterator() {
throw new AssertionError("should never be called");
}
@Override
Map<K, Collection<V>> createAsMap() {
return new Multimaps.AsMap<K, V>(this);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.HashMap;
/**
* Multiset implementation backed by a {@link HashMap}.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> {
/**
* Creates a new, empty {@code HashMultiset} using the default initial
* capacity.
*/
public static <E> HashMultiset<E> create() {
return new HashMultiset<E>();
}
/**
* Creates a new, empty {@code HashMultiset} with the specified expected
* number of distinct elements.
*
* @param distinctElements the expected number of distinct elements
* @throws IllegalArgumentException if {@code distinctElements} is negative
*/
public static <E> HashMultiset<E> create(int distinctElements) {
return new HashMultiset<E>(distinctElements);
}
/**
* Creates a new {@code HashMultiset} containing the specified elements.
*
* <p>This implementation is highly efficient when {@code elements} is itself
* a {@link Multiset}.
*
* @param elements the elements that the multiset should contain
*/
public static <E> HashMultiset<E> create(Iterable<? extends E> elements) {
HashMultiset<E> multiset =
create(Multisets.inferDistinctElements(elements));
Iterables.addAll(multiset, elements);
return multiset;
}
private HashMultiset() {
super(new HashMap<E, Count>());
}
private HashMultiset(int distinctElements) {
super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.EnumMap;
import java.util.Map;
/**
* A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values
* are not permitted. An {@code EnumBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
private transient Class<V> valueType;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value
* types.
*
* @param keyType the key type
* @param valueType the value type
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Class<K> keyType, Class<V> valueType) {
return new EnumBiMap<K, V>(keyType, valueType);
}
/**
* Returns a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumBiMap}, the new bimap has the same types as
* the provided map. Otherwise, the specified map must contain at least one
* mapping, in order to determine the key and value types.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V>
create(Map<K, V> map) {
EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map));
bimap.putAll(map);
return bimap;
}
private EnumBiMap(Class<K> keyType, Class<V> valueType) {
super(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)),
WellBehavedMap.wrap(new EnumMap<V, K>(valueType)));
this.keyType = keyType;
this.valueType = valueType;
}
static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<K, ?>) map).keyType();
}
if (map instanceof EnumHashBiMap) {
return ((EnumHashBiMap<K, ?>) map).keyType();
}
checkArgument(!map.isEmpty());
return map.keySet().iterator().next().getDeclaringClass();
}
private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<?, V>) map).valueType;
}
checkArgument(!map.isEmpty());
return map.values().iterator().next().getDeclaringClass();
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
/** Returns the associated value type. */
public Class<V> valueType() {
return valueType;
}
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override
V checkValue(V value) {
return checkNotNull(value);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
/**
* GWT emulated version of {@link ImmutableList}.
* TODO(cpovirk): more doc
*
* @author Hayward Chan
*/
abstract class ForwardingImmutableList<E> extends ImmutableList<E> {
ForwardingImmutableList() {
}
abstract List<E> delegateList();
public int indexOf(@Nullable Object object) {
return delegateList().indexOf(object);
}
public int lastIndexOf(@Nullable Object object) {
return delegateList().lastIndexOf(object);
}
public E get(int index) {
return delegateList().get(index);
}
public ImmutableList<E> subList(int fromIndex, int toIndex) {
return unsafeDelegateList(delegateList().subList(fromIndex, toIndex));
}
@Override public Object[] toArray() {
// Note that ArrayList.toArray() doesn't work here because it returns E[]
// instead of Object[].
return delegateList().toArray(new Object[size()]);
}
@Override public boolean equals(Object obj) {
return delegateList().equals(obj);
}
@Override public int hashCode() {
return delegateList().hashCode();
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegateList().iterator());
}
@Override public boolean contains(@Nullable Object object) {
return object != null && delegateList().contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return delegateList().containsAll(targets);
}
public int size() {
return delegateList().size();
}
@Override public boolean isEmpty() {
return delegateList().isEmpty();
}
@Override public <T> T[] toArray(T[] other) {
return delegateList().toArray(other);
}
@Override public String toString() {
return delegateList().toString();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static java.util.Collections.unmodifiableList;
import java.util.List;
/**
* GWT emulated version of {@link RegularImmutableList}.
*
* @author Hayward Chan
*/
class RegularImmutableList<E> extends ForwardingImmutableList<E> {
private final List<E> delegate;
RegularImmutableList(List<E> delegate) {
// TODO(cpovirk): avoid redundant unmodifiableList wrapping
this.delegate = unmodifiableList(delegate);
}
@Override List<E> delegateList() {
return delegate;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.annotation.Nullable;
/**
* GWT emulation of {@link ImmutableSortedSet}.
*
* @author Hayward Chan
*/
public abstract class ImmutableSortedSet<E>
extends ForwardingImmutableSet<E> implements SortedSet<E>, SortedIterable<E> {
// TODO(cpovirk): split into ImmutableSortedSet/ForwardingImmutableSortedSet?
// In the non-emulated source, this is in ImmutableSortedSetFauxverideShim,
// which overrides ImmutableSet & which ImmutableSortedSet extends.
// It is necessary here because otherwise the builder() method
// would be inherited from the emulated ImmutableSet.
@Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() {
throw new UnsupportedOperationException();
}
// TODO: Can we find a way to remove this @SuppressWarnings even for eclipse?
@SuppressWarnings("unchecked")
private static final Comparator NATURAL_ORDER = Ordering.natural();
@SuppressWarnings("unchecked")
private static final ImmutableSortedSet<Object> NATURAL_EMPTY_SET =
new EmptyImmutableSortedSet<Object>(NATURAL_ORDER);
@SuppressWarnings("unchecked")
private static <E> ImmutableSortedSet<E> emptySet() {
return (ImmutableSortedSet<E>) NATURAL_EMPTY_SET;
}
static <E> ImmutableSortedSet<E> emptySet(
Comparator<? super E> comparator) {
checkNotNull(comparator);
if (NATURAL_ORDER.equals(comparator)) {
return emptySet();
} else {
return new EmptyImmutableSortedSet<E>(comparator);
}
}
public static <E> ImmutableSortedSet<E> of() {
return emptySet();
}
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E element) {
return ofInternal(Ordering.natural(), element);
}
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2) {
return ofInternal(Ordering.natural(), e1, e2);
}
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3) {
return ofInternal(Ordering.natural(), e1, e2, e3);
}
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4) {
return ofInternal(Ordering.natural(), e1, e2, e3, e4);
}
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5) {
return ofInternal(Ordering.natural(), e1, e2, e3, e4, e5);
}
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
int size = remaining.length + 6;
List<E> all = new ArrayList<E>(size);
Collections.addAll(all, e1, e2, e3, e4, e5, e6);
Collections.addAll(all, remaining);
// This is messed up. See TODO at top of file.
return ofInternal(Ordering.natural(), (E[]) all.toArray(new Comparable[0]));
}
@Deprecated
public
static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
E[] elements) {
return copyOf(elements);
}
private static <E> ImmutableSortedSet<E> ofInternal(
Comparator<? super E> comparator, E... elements) {
checkNotNull(elements);
switch (elements.length) {
case 0:
return emptySet(comparator);
default:
SortedSet<E> delegate = new TreeSet<E>(comparator);
for (E element : elements) {
checkNotNull(element);
delegate.add(element);
}
return new RegularImmutableSortedSet<E>(delegate, false);
}
}
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
Collection<? extends E> elements) {
return copyOfInternal(Ordering.natural(), elements, false);
}
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
Iterable<? extends E> elements) {
return copyOfInternal(Ordering.natural(), elements, false);
}
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
Iterator<? extends E> elements) {
return copyOfInternal(Ordering.natural(), elements);
}
public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(
E[] elements) {
return ofInternal(Ordering.natural(), elements);
}
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterable<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements, false);
}
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Collection<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements, false);
}
public static <E> ImmutableSortedSet<E> copyOf(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
checkNotNull(comparator);
return copyOfInternal(comparator, elements);
}
@SuppressWarnings("unchecked")
public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
Comparator<? super E> comparator = sortedSet.comparator();
if (comparator == null) {
comparator = NATURAL_ORDER;
}
return copyOfInternal(comparator, sortedSet.iterator());
}
private static <E> ImmutableSortedSet<E> copyOfInternal(
Comparator<? super E> comparator, Iterable<? extends E> elements,
boolean fromSortedSet) {
checkNotNull(comparator);
boolean hasSameComparator
= fromSortedSet || hasSameComparator(elements, comparator);
if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
@SuppressWarnings("unchecked")
ImmutableSortedSet<E> result = (ImmutableSortedSet<E>) elements;
boolean isSubset = (result instanceof RegularImmutableSortedSet)
&& ((RegularImmutableSortedSet) result).isSubset;
if (!isSubset) {
// Only return the original copy if this immutable sorted set isn't
// a subset of another, to avoid memory leak.
return result;
}
}
return copyOfInternal(comparator, elements.iterator());
}
private static <E> ImmutableSortedSet<E> copyOfInternal(
Comparator<? super E> comparator, Iterator<? extends E> elements) {
checkNotNull(comparator);
if (!elements.hasNext()) {
return emptySet(comparator);
}
SortedSet<E> delegate = new TreeSet<E>(comparator);
while (elements.hasNext()) {
E element = elements.next();
checkNotNull(element);
delegate.add(element);
}
return new RegularImmutableSortedSet<E>(delegate, false);
}
private static boolean hasSameComparator(
Iterable<?> elements, Comparator<?> comparator) {
if (elements instanceof SortedSet) {
SortedSet<?> sortedSet = (SortedSet<?>) elements;
Comparator<?> comparator2 = sortedSet.comparator();
return (comparator2 == null)
? comparator == Ordering.natural()
: comparator.equals(comparator2);
}
return false;
}
// Assumes that delegate doesn't have null elements and comparator.
static <E> ImmutableSortedSet<E> unsafeDelegateSortedSet(
SortedSet<E> delegate, boolean isSubset) {
return delegate.isEmpty()
? emptySet(delegate.comparator())
: new RegularImmutableSortedSet<E>(delegate, isSubset);
}
// This reference is only used by GWT compiler to infer the elements of the
// set that needs to be serialized.
private Comparator<E> unusedComparatorForSerialization;
private E unusedElementForSerialization;
private transient final SortedSet<E> sortedDelegate;
/**
* Scary constructor for ContiguousSet. This constructor (in this file, the
* GWT emulation of ImmutableSortedSet) creates an empty sortedDelegate,
* which, in a vacuum, sets this object's contents to empty. By contrast,
* the non-GWT constructor with the same signature uses the comparator only
* as a comparator. It does NOT assume empty contents. (It requires an
* implementation of iterator() to define its contents, and methods like
* contains() are implemented in terms of that method (though they will
* likely be overridden by subclasses for performance reasons).) This means
* that a call to this method have can different behavior in GWT and non-GWT
* environments UNLESS subclasses are careful to always override all methods
* implemented in terms of sortedDelegate (except comparator()).
*/
ImmutableSortedSet(Comparator<? super E> comparator) {
this(Sets.newTreeSet(comparator));
}
ImmutableSortedSet(SortedSet<E> sortedDelegate) {
super(sortedDelegate);
this.sortedDelegate = Collections.unmodifiableSortedSet(sortedDelegate);
}
public Comparator<? super E> comparator() {
return sortedDelegate.comparator();
}
@Override // needed to unify SortedIterable and Collection iterator() methods
public UnmodifiableIterator<E> iterator() {
return super.iterator();
}
@Override
public Object[] toArray() {
return ObjectArrays.toArrayImpl(this);
}
@Override
public <T> T[] toArray(T[] other) {
return ObjectArrays.toArrayImpl(this, other);
}
@Override public boolean contains(@Nullable Object object) {
try {
// This set never contains null. We need to explicitly check here
// because some comparator might throw NPE (e.g. the natural ordering).
return object != null && sortedDelegate.contains(object);
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean containsAll(Collection<?> targets) {
for (Object target : targets) {
if (target == null) {
// This set never contains null. We need to explicitly check here
// because some comparator might throw NPE (e.g. the natural ordering).
return false;
}
}
try {
return sortedDelegate.containsAll(targets);
} catch (ClassCastException e) {
return false;
}
}
public E first() {
return sortedDelegate.first();
}
public ImmutableSortedSet<E> headSet(E toElement) {
checkNotNull(toElement);
try {
return unsafeDelegateSortedSet(sortedDelegate.headSet(toElement), true);
} catch (IllegalArgumentException e) {
return emptySet(comparator());
}
}
E higher(E e) {
checkNotNull(e);
Iterator<E> iterator = tailSet(e).iterator();
while (iterator.hasNext()) {
E higher = iterator.next();
if (comparator().compare(e, higher) < 0) {
return higher;
}
}
return null;
}
ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
checkNotNull(toElement);
if (inclusive) {
E tmp = higher(toElement);
if (tmp == null) {
return this;
}
toElement = tmp;
}
return headSet(toElement);
}
public E last() {
return sortedDelegate.last();
}
public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
ImmutableSortedSet<E> subSet(E fromElement, boolean fromInclusive, E toElement,
boolean toInclusive) {
checkNotNull(fromElement);
checkNotNull(toElement);
int cmp = comparator().compare(fromElement, toElement);
checkArgument(cmp <= 0, "fromElement (%s) is less than toElement (%s)", fromElement, toElement);
if (cmp == 0 && !(fromInclusive && toInclusive)) {
return emptySet(comparator());
}
return tailSet(fromElement, fromInclusive).headSet(toElement, toInclusive);
}
public ImmutableSortedSet<E> tailSet(E fromElement) {
checkNotNull(fromElement);
try {
return unsafeDelegateSortedSet(sortedDelegate.tailSet(fromElement), true);
} catch (IllegalArgumentException e) {
return emptySet(comparator());
}
}
ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
checkNotNull(fromElement);
if (!inclusive) {
E tmp = higher(fromElement);
if (tmp == null) {
return emptySet(comparator());
}
fromElement = tmp;
}
return tailSet(fromElement);
}
public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
return new Builder<E>(comparator);
}
public static <E extends Comparable<?>> Builder<E> reverseOrder() {
return new Builder<E>(Ordering.natural().reverse());
}
public static <E extends Comparable<?>> Builder<E> naturalOrder() {
return new Builder<E>(Ordering.natural());
}
public static final class Builder<E> extends ImmutableSet.Builder<E> {
private final Comparator<? super E> comparator;
public Builder(Comparator<? super E> comparator) {
this.comparator = checkNotNull(comparator);
}
@Override public Builder<E> add(E element) {
super.add(element);
return this;
}
@Override public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override public ImmutableSortedSet<E> build() {
return copyOfInternal(comparator, contents.iterator());
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* A multiset which maintains the ordering of its elements, according to either their natural order
* or an explicit {@link Comparator}. In all cases, this implementation uses
* {@link Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to
* determine equivalence of instances.
*
* <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the
* {@link Comparable} class specification. Otherwise, the resulting multiset will violate the
* {@link java.util.Collection} contract, which is specified in terms of {@link Object#equals}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset">
* {@code Multiset}</a>.
*
* @author Louis Wasserman
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable {
/**
* Creates a new, empty multiset, sorted according to the elements' natural order. All elements
* inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all
* such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the
* user attempts to add an element to the multiset that violates this constraint (for example,
* the user attempts to add a string element to a set whose elements are integers), the
* {@code add(Object)} call will throw a {@code ClassCastException}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create() {
return new TreeMultiset<E>(Ordering.natural());
}
/**
* Creates a new, empty multiset, sorted according to the specified comparator. All elements
* inserted into the multiset must be <i>mutually comparable</i> by the specified comparator:
* {@code comparator.compare(e1,
* e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in
* the multiset. If the user attempts to add an element to the multiset that violates this
* constraint, the {@code add(Object)} call will throw a {@code ClassCastException}.
*
* @param comparator
* the comparator that will be used to sort this multiset. A null value indicates that
* the elements' <i>natural ordering</i> should be used.
*/
@SuppressWarnings("unchecked")
public static <E> TreeMultiset<E> create(@Nullable Comparator<? super E> comparator) {
return (comparator == null)
? new TreeMultiset<E>((Comparator) Ordering.natural())
: new TreeMultiset<E>(comparator);
}
/**
* Creates an empty multiset containing the given initial elements, sorted according to the
* elements' natural order.
*
* <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
*
* <p>The type specification is {@code <E extends Comparable>}, instead of the more specific
* {@code <E extends Comparable<? super E>>}, to support classes defined without generics.
*/
public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) {
TreeMultiset<E> multiset = create();
Iterables.addAll(multiset, elements);
return multiset;
}
private final transient Reference<AvlNode<E>> rootReference;
private final transient GeneralRange<E> range;
private final transient AvlNode<E> header;
TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) {
super(range.comparator());
this.rootReference = rootReference;
this.range = range;
this.header = endLink;
}
TreeMultiset(Comparator<? super E> comparator) {
super(comparator);
this.range = GeneralRange.all(comparator);
this.header = new AvlNode<E>(null, 1);
successor(header, header);
this.rootReference = new Reference<AvlNode<E>>();
}
/**
* A function which can be summed across a subtree.
*/
private enum Aggregate {
SIZE {
@Override
int nodeAggregate(AvlNode<?> node) {
return node.elemCount;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.totalCount;
}
},
DISTINCT {
@Override
int nodeAggregate(AvlNode<?> node) {
return 1;
}
@Override
long treeAggregate(@Nullable AvlNode<?> root) {
return (root == null) ? 0 : root.distinctElements;
}
};
abstract int nodeAggregate(AvlNode<?> node);
abstract long treeAggregate(@Nullable AvlNode<?> root);
}
private long aggregateForEntries(Aggregate aggr) {
AvlNode<E> root = rootReference.get();
long total = aggr.treeAggregate(root);
if (range.hasLowerBound()) {
total -= aggregateBelowRange(aggr, root);
}
if (range.hasUpperBound()) {
total -= aggregateAboveRange(aggr, root);
}
return total;
}
private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getLowerEndpoint(), node.elem);
if (cmp < 0) {
return aggregateBelowRange(aggr, node.left);
} else if (cmp == 0) {
switch (range.getLowerBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left);
case CLOSED:
return aggr.treeAggregate(node.left);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node)
+ aggregateBelowRange(aggr, node.right);
}
}
private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode<E> node) {
if (node == null) {
return 0;
}
int cmp = comparator().compare(range.getUpperEndpoint(), node.elem);
if (cmp > 0) {
return aggregateAboveRange(aggr, node.right);
} else if (cmp == 0) {
switch (range.getUpperBoundType()) {
case OPEN:
return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right);
case CLOSED:
return aggr.treeAggregate(node.right);
default:
throw new AssertionError();
}
} else {
return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node)
+ aggregateAboveRange(aggr, node.left);
}
}
@Override
public int size() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE));
}
@Override
int distinctElements() {
return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT));
}
@Override
public int count(@Nullable Object element) {
try {
@SuppressWarnings("unchecked")
E e = (E) element;
AvlNode<E> root = rootReference.get();
if (!range.contains(e) || root == null) {
return 0;
}
return root.count(comparator(), e);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
}
@Override
public int add(@Nullable E element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
comparator().compare(element, element);
AvlNode<E> newRoot = new AvlNode<E>(element, occurrences);
successor(header, newRoot, header);
rootReference.checkAndSet(root, newRoot);
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences);
if (occurrences == 0) {
return count(element);
}
AvlNode<E> root = rootReference.get();
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot;
try {
@SuppressWarnings("unchecked")
E e = (E) element;
if (!range.contains(e) || root == null) {
return 0;
}
newRoot = root.remove(comparator(), e, occurrences, result);
} catch (ClassCastException e) {
return 0;
} catch (NullPointerException e) {
return 0;
}
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public int setCount(@Nullable E element, int count) {
checkArgument(count >= 0);
if (!range.contains(element)) {
checkArgument(count == 0);
return 0;
}
AvlNode<E> root = rootReference.get();
if (root == null) {
if (count > 0) {
add(element, count);
}
return 0;
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, count, result);
rootReference.checkAndSet(root, newRoot);
return result[0];
}
@Override
public boolean setCount(@Nullable E element, int oldCount, int newCount) {
checkArgument(newCount >= 0);
checkArgument(oldCount >= 0);
checkArgument(range.contains(element));
AvlNode<E> root = rootReference.get();
if (root == null) {
if (oldCount == 0) {
if (newCount > 0) {
add(element, newCount);
}
return true;
} else {
return false;
}
}
int[] result = new int[1]; // used as a mutable int reference to hold result
AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result);
rootReference.checkAndSet(root, newRoot);
return result[0] == oldCount;
}
private Entry<E> wrapEntry(final AvlNode<E> baseEntry) {
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return baseEntry.getElement();
}
@Override
public int getCount() {
int result = baseEntry.getCount();
if (result == 0) {
return count(getElement());
} else {
return result;
}
}
};
}
/**
* Returns the first node in the tree that is in range.
*/
@Nullable private AvlNode<E> firstNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasLowerBound()) {
E endpoint = range.getLowerEndpoint();
node = rootReference.get().ceiling(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getLowerBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.succ;
}
} else {
node = header.succ;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Nullable private AvlNode<E> lastNode() {
AvlNode<E> root = rootReference.get();
if (root == null) {
return null;
}
AvlNode<E> node;
if (range.hasUpperBound()) {
E endpoint = range.getUpperEndpoint();
node = rootReference.get().floor(comparator(), endpoint);
if (node == null) {
return null;
}
if (range.getUpperBoundType() == BoundType.OPEN
&& comparator().compare(endpoint, node.getElement()) == 0) {
node = node.pred;
}
} else {
node = header.pred;
}
return (node == header || !range.contains(node.getElement())) ? null : node;
}
@Override
Iterator<Entry<E>> entryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = firstNode();
Entry<E> prevEntry;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooHigh(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.succ == header) {
current = null;
} else {
current = current.succ;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
Iterator<Entry<E>> descendingEntryIterator() {
return new Iterator<Entry<E>>() {
AvlNode<E> current = lastNode();
Entry<E> prevEntry = null;
@Override
public boolean hasNext() {
if (current == null) {
return false;
} else if (range.tooLow(current.getElement())) {
current = null;
return false;
} else {
return true;
}
}
@Override
public Entry<E> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Entry<E> result = wrapEntry(current);
prevEntry = result;
if (current.pred == header) {
current = null;
} else {
current = current.pred;
}
return result;
}
@Override
public void remove() {
checkState(prevEntry != null);
setCount(prevEntry.getElement(), 0);
prevEntry = null;
}
};
}
@Override
public SortedMultiset<E> headMultiset(@Nullable E upperBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.upTo(
comparator(),
upperBound,
boundType)), header);
}
@Override
public SortedMultiset<E> tailMultiset(@Nullable E lowerBound, BoundType boundType) {
return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.downTo(
comparator(),
lowerBound,
boundType)), header);
}
static int distinctElements(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.distinctElements;
}
private static final class Reference<T> {
@Nullable private T value;
@Nullable public T get() {
return value;
}
public void checkAndSet(@Nullable T expected, T newValue) {
if (value != expected) {
throw new ConcurrentModificationException();
}
value = newValue;
}
}
private static final class AvlNode<E> extends Multisets.AbstractEntry<E> {
@Nullable private final E elem;
// elemCount is 0 iff this node has been deleted.
private int elemCount;
private int distinctElements;
private long totalCount;
private int height;
private AvlNode<E> left;
private AvlNode<E> right;
private AvlNode<E> pred;
private AvlNode<E> succ;
AvlNode(@Nullable E elem, int elemCount) {
checkArgument(elemCount > 0);
this.elem = elem;
this.elemCount = elemCount;
this.totalCount = elemCount;
this.distinctElements = 1;
this.height = 1;
this.left = null;
this.right = null;
}
public int count(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? 0 : left.count(comparator, e);
} else if (cmp > 0) {
return (right == null) ? 0 : right.count(comparator, e);
} else {
return elemCount;
}
}
private AvlNode<E> addRightChild(E e, int count) {
right = new AvlNode<E>(e, count);
successor(this, right, succ);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
private AvlNode<E> addLeftChild(E e, int count) {
left = new AvlNode<E>(e, count);
successor(pred, left, this);
height = Math.max(2, height);
distinctElements++;
totalCount += count;
return this;
}
AvlNode<E> add(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
/*
* It speeds things up considerably to unconditionally add count to totalCount here,
* but that destroys failure atomicity in the case of count overflow. =(
*/
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return addLeftChild(e, count);
}
int initHeight = initLeft.height;
left = initLeft.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (left.height == initHeight) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return addRightChild(e, count);
}
int initHeight = initRight.height;
right = initRight.add(comparator, e, count, result);
if (result[0] == 0) {
distinctElements++;
}
this.totalCount += count;
return (right.height == initHeight) ? this : rebalance();
}
// adding count to me! No rebalance possible.
result[0] = elemCount;
long resultCount = (long) elemCount + count;
checkArgument(resultCount <= Integer.MAX_VALUE);
this.elemCount += count;
this.totalCount += count;
return this;
}
AvlNode<E> remove(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return this;
}
left = initLeft.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return (result[0] == 0) ? this : rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return this;
}
right = initRight.remove(comparator, e, count, result);
if (result[0] > 0) {
if (count >= result[0]) {
this.distinctElements--;
this.totalCount -= result[0];
} else {
this.totalCount -= count;
}
}
return rebalance();
}
// removing count from me!
result[0] = elemCount;
if (count >= elemCount) {
return deleteMe();
} else {
this.elemCount -= count;
this.totalCount -= count;
return this;
}
}
AvlNode<E> setCount(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
return (count > 0) ? addLeftChild(e, count) : this;
}
left = initLeft.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
return (count > 0) ? addRightChild(e, count) : this;
}
right = initRight.setCount(comparator, e, count, result);
if (count == 0 && result[0] != 0) {
this.distinctElements--;
} else if (count > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += count - result[0];
return rebalance();
}
// setting my count
result[0] = elemCount;
if (count == 0) {
return deleteMe();
}
this.totalCount += count - elemCount;
this.elemCount = count;
return this;
}
AvlNode<E> setCount(
Comparator<? super E> comparator,
@Nullable E e,
int expectedCount,
int newCount,
int[] result) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
AvlNode<E> initLeft = left;
if (initLeft == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addLeftChild(e, newCount);
}
return this;
}
left = initLeft.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
} else if (cmp > 0) {
AvlNode<E> initRight = right;
if (initRight == null) {
result[0] = 0;
if (expectedCount == 0 && newCount > 0) {
return addRightChild(e, newCount);
}
return this;
}
right = initRight.setCount(comparator, e, expectedCount, newCount, result);
if (result[0] == expectedCount) {
if (newCount == 0 && result[0] != 0) {
this.distinctElements--;
} else if (newCount > 0 && result[0] == 0) {
this.distinctElements++;
}
this.totalCount += newCount - result[0];
}
return rebalance();
}
// setting my count
result[0] = elemCount;
if (expectedCount == elemCount) {
if (newCount == 0) {
return deleteMe();
}
this.totalCount += newCount - elemCount;
this.elemCount = newCount;
}
return this;
}
private AvlNode<E> deleteMe() {
int oldElemCount = this.elemCount;
this.elemCount = 0;
successor(pred, succ);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else if (left.height >= right.height) {
AvlNode<E> newTop = pred;
// newTop is the maximum node in my left subtree
newTop.left = left.removeMax(newTop);
newTop.right = right;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
} else {
AvlNode<E> newTop = succ;
newTop.right = right.removeMin(newTop);
newTop.left = left;
newTop.distinctElements = distinctElements - 1;
newTop.totalCount = totalCount - oldElemCount;
return newTop.rebalance();
}
}
// Removes the minimum node from this subtree to be reused elsewhere
private AvlNode<E> removeMin(AvlNode<E> node) {
if (left == null) {
return right;
} else {
left = left.removeMin(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
// Removes the maximum node from this subtree to be reused elsewhere
private AvlNode<E> removeMax(AvlNode<E> node) {
if (right == null) {
return left;
} else {
right = right.removeMax(node);
distinctElements--;
totalCount -= node.elemCount;
return rebalance();
}
}
private void recomputeMultiset() {
this.distinctElements = 1 + TreeMultiset.distinctElements(left)
+ TreeMultiset.distinctElements(right);
this.totalCount = elemCount + totalCount(left) + totalCount(right);
}
private void recomputeHeight() {
this.height = 1 + Math.max(height(left), height(right));
}
private void recompute() {
recomputeMultiset();
recomputeHeight();
}
private AvlNode<E> rebalance() {
switch (balanceFactor()) {
case -2:
if (right.balanceFactor() > 0) {
right = right.rotateRight();
}
return rotateLeft();
case 2:
if (left.balanceFactor() < 0) {
left = left.rotateLeft();
}
return rotateRight();
default:
recomputeHeight();
return this;
}
}
private int balanceFactor() {
return height(left) - height(right);
}
private AvlNode<E> rotateLeft() {
checkState(right != null);
AvlNode<E> newTop = right;
this.right = newTop.left;
newTop.left = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private AvlNode<E> rotateRight() {
checkState(left != null);
AvlNode<E> newTop = left;
this.left = newTop.right;
newTop.right = this;
newTop.totalCount = this.totalCount;
newTop.distinctElements = this.distinctElements;
this.recompute();
newTop.recomputeHeight();
return newTop;
}
private static long totalCount(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.totalCount;
}
private static int height(@Nullable AvlNode<?> node) {
return (node == null) ? 0 : node.height;
}
@Nullable private AvlNode<E> ceiling(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp < 0) {
return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (right == null) ? null : right.ceiling(comparator, e);
}
}
@Nullable private AvlNode<E> floor(Comparator<? super E> comparator, E e) {
int cmp = comparator.compare(e, elem);
if (cmp > 0) {
return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this);
} else if (cmp == 0) {
return this;
} else {
return (left == null) ? null : left.floor(comparator, e);
}
}
@Override
public E getElement() {
return elem;
}
@Override
public int getCount() {
return elemCount;
}
@Override
public String toString() {
return Multisets.immutableEntry(getElement(), getCount()).toString();
}
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b) {
a.succ = b;
b.pred = a;
}
private static <T> void successor(AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) {
successor(a, b);
successor(b, c);
}
/*
* TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that
* calls the comparator to compare the two keys. If that change is made,
* AbstractMultiset.equals() can simply check whether two multisets have equal entry sets.
*/
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Set;
/**
* GWT emulation of {@link RegularImmutableSet}.
*
* @author Hayward Chan
*/
final class RegularImmutableSet<E> extends ForwardingImmutableSet<E> {
RegularImmutableSet(Set<E> delegate) {
super(delegate);
// Required for GWT deserialization because the server-side implementation
// requires this.
checkArgument(delegate.size() >= 2);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Map;
/**
* GWt emulation of {@link RegularImmutableMap}.
*
* @author Hayward Chan
*/
final class RegularImmutableMap<K, V> extends ForwardingImmutableMap<K, V> {
RegularImmutableMap(Map<? extends K, ? extends V> delegate) {
super(delegate);
}
RegularImmutableMap(Entry<? extends K, ? extends V>... entries) {
super(entries);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
/**
* GWT implementation of {@link ImmutableSet} that forwards to another {@code Set} implementation.
*
* @author Hayward Chan
*/
@SuppressWarnings("serial") // Serialization only done in GWT.
public abstract class ForwardingImmutableSet<E> extends ImmutableSet<E> {
private final transient Set<E> delegate;
ForwardingImmutableSet(Set<E> delegate) {
// TODO(cpovirk): are we over-wrapping?
this.delegate = Collections.unmodifiableSet(delegate);
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.unmodifiableIterator(delegate.iterator());
}
@Override public boolean contains(@Nullable Object object) {
return object != null && delegate.contains(object);
}
@Override public boolean containsAll(Collection<?> targets) {
return delegate.containsAll(targets);
}
@Override public int size() {
return delegate.size();
}
@Override public boolean isEmpty() {
return delegate.isEmpty();
}
@Override public Object[] toArray() {
return delegate.toArray();
}
@Override public <T> T[] toArray(T[] other) {
return delegate.toArray(other);
}
@Override public String toString() {
return delegate.toString();
}
// TODO(cpovirk): equals(), as well, in case it's any faster than Sets.equalsImpl?
@Override public int hashCode() {
return delegate.hashCode();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of
* {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts
* {@link Lists}, {@link Sets} and {@link Queues}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps">
* {@code Maps}</a>.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Maps {
private Maps() {}
private enum EntryFunction implements Function<Entry<?, ?>, Object> {
KEY {
@Override
@Nullable
public Object apply(Entry<?, ?> entry) {
return entry.getKey();
}
},
VALUE {
@Override
@Nullable
public Object apply(Entry<?, ?> entry) {
return entry.getValue();
}
};
}
@SuppressWarnings("unchecked")
static <K> Function<Entry<K, ?>, K> keyFunction() {
return (Function) EntryFunction.KEY;
}
@SuppressWarnings("unchecked")
static <V> Function<Entry<?, V>, V> valueFunction() {
return (Function) EntryFunction.VALUE;
}
static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
return Iterators.transform(entryIterator, Maps.<K>keyFunction());
}
static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
return Iterators.transform(entryIterator, Maps.<V>valueFunction());
}
static <K, V> UnmodifiableIterator<V> valueIterator(
final UnmodifiableIterator<Entry<K, V>> entryIterator) {
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
/**
* Returns an immutable map instance containing the given entries.
* Internally, the returned map will be backed by an {@link EnumMap}.
*
* <p>The iteration order of the returned map follows the enum's iteration
* order, not the order in which the elements appear in the given map.
*
* @param map the map to make an immutable copy of
* @return an immutable map containing those entries
* @since 14.0
*/
@GwtCompatible(serializable = true)
@Beta
public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
Map<K, ? extends V> map) {
if (map instanceof ImmutableEnumMap) {
@SuppressWarnings("unchecked") // safe covariant cast
ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
return result;
} else if (map.isEmpty()) {
return ImmutableMap.of();
} else {
for (Map.Entry<K, ? extends V> entry : map.entrySet()) {
checkNotNull(entry.getKey());
checkNotNull(entry.getValue());
}
return ImmutableEnumMap.asImmutable(new EnumMap<K, V>(map));
}
}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
* #newEnumMap} instead.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity"
* that it <i>should</i> hold {@code expectedSize} elements without growth.
* This behavior cannot be broadly guaranteed, but it is observed to be true
* for OpenJDK 1.6. It also can't be guaranteed that the method isn't
* inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of elements you expect to add to the
* returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code
* expectedSize} elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
int expectedSize) {
return new HashMap<K, V>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as
* long as it grows no larger than expectedSize and the load factor is >= its
* default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkArgument(expectedSize >= 0);
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
return expectedSize + expectedSize / 3;
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as
* the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link
* #newEnumMap} instead.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code
* map}
*/
public static <K, V> HashMap<K, V> newHashMap(
Map<? extends K, ? extends V> map) {
return new HashMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap}
* instance.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#of()} instead.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance
* with the same mappings as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableMap#copyOf(Map)} instead.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from
* {@code map}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(
Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
}
/**
* Returns a general-purpose instance of {@code ConcurrentMap}, which supports
* all optional operations of the ConcurrentMap interface. It does not permit
* null keys or values. It is serializable.
*
* <p>This is currently accomplished by calling {@link MapMaker#makeMap()}.
*
* <p>It is preferable to use {@code MapMaker} directly (rather than through
* this method), as it presents numerous useful configuration options,
* such as the concurrency level, load factor, key/value reference types,
* and value computation.
*
* @return a new, empty {@code ConcurrentMap}
* @since 3.0
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new MapMaker().<K, V>makeMap();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural
* ordering of its elements.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#of()} instead.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
/**
* Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as
* the specified map and using the same ordering as the specified map.
*
* <p><b>Note:</b> if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
* @param map the sorted map whose mappings are to be placed in the new map
* and whose comparator is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code
* map} and using the comparator of {@code map}
*/
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given
* comparator.
*
* <p><b>Note:</b> if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(
@Nullable Comparator<C> comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator<Class<?>> comparator = null;
// Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
return new TreeMap<K, V>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<K, V>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code
* map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap}
* instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(
Map<K, ? extends V> map) {
return new EnumMap<K, V>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* <p><b>Note:</b>If you only need to know whether two maps have the same
* mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
@SuppressWarnings("unchecked")
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
if (left instanceof SortedMap) {
SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
SortedMapDifference<K, V> result = difference(sortedLeft, right);
return result;
}
return difference(left, right, Equivalence.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable
* snapshot of the state of the maps at the time this method is called. It
* will never change, even if the maps change at a later time.
*
* <p>Values are compared using a provided equivalence, in the case of
* equality, the value on the 'left' is returned in the difference.
*
* <p>Since this method uses {@code HashMap} instances internally, the keys of
* the supplied maps must be well-behaved with respect to
* {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare
* values
* @return the difference between the two maps
* @since 10.0
*/
@Beta
public static <K, V> MapDifference<K, V> difference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map<K, V> onlyOnLeft = newHashMap();
Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down
Map<K, V> onBoth = newHashMap();
Map<K, MapDifference.ValueDifference<V>> differences = newHashMap();
doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
return new MapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static <K, V> void doDifference(
Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
Equivalence<? super V> valueEquivalence,
Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, MapDifference.ValueDifference<V>> differences) {
for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
V rightValue = onlyOnRight.remove(leftKey);
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
differences.put(
leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
}
private static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
if (map instanceof SortedMap) {
return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
} else {
return Collections.unmodifiableMap(map);
}
}
static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
final Map<K, V> onlyOnLeft;
final Map<K, V> onlyOnRight;
final Map<K, V> onBoth;
final Map<K, ValueDifference<V>> differences;
MapDifferenceImpl(Map<K, V> onlyOnLeft,
Map<K, V> onlyOnRight, Map<K, V> onBoth,
Map<K, ValueDifference<V>> differences) {
this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
this.onlyOnRight = unmodifiableMap(onlyOnRight);
this.onBoth = unmodifiableMap(onBoth);
this.differences = unmodifiableMap(differences);
}
@Override
public boolean areEqual() {
return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
}
@Override
public Map<K, V> entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map<K, V> entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map<K, V> entriesInCommon() {
return onBoth;
}
@Override
public Map<K, ValueDifference<V>> entriesDiffering() {
return differences;
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference<?, ?> other = (MapDifference<?, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(),
entriesInCommon(), entriesDiffering());
}
@Override public String toString() {
if (areEqual()) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl<V>
implements MapDifference.ValueDifference<V> {
private final V left;
private final V right;
static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
return new ValueDifferenceImpl<V>(left, right);
}
private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
this.left = left;
this.right = right;
}
@Override
public V leftValue() {
return left;
}
@Override
public V rightValue() {
return right;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference<?> that =
(MapDifference.ValueDifference<?>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(left, right);
}
@Override public String toString() {
return "(" + left + ", " + right + ")";
}
}
/**
* Computes the difference between two sorted maps, using the comparator of
* the left map, or {@code Ordering.natural()} if the left map uses the
* natural ordering of its elements. This difference is an immutable snapshot
* of the state of the maps at the time this method is called. It will never
* change, even if the maps change at a later time.
*
* <p>Since this method uses {@code TreeMap} instances internally, the keys of
* the right map must all compare as distinct according to the comparator
* of the left map.
*
* <p><b>Note:</b>If you only need to know whether two sorted maps have the
* same mappings, call {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static <K, V> SortedMapDifference<K, V> difference(
SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator<? super K> comparator = orNaturalOrder(left.comparator());
SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
SortedMap<K, MapDifference.ValueDifference<V>> differences =
Maps.newTreeMap(comparator);
doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
implements SortedMapDifference<K, V> {
SortedMapDifferenceImpl(SortedMap<K, V> onlyOnLeft,
SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth,
SortedMap<K, ValueDifference<V>> differences) {
super(onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override public SortedMap<K, ValueDifference<V>> entriesDiffering() {
return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
}
@Override public SortedMap<K, V> entriesInCommon() {
return (SortedMap<K, V>) super.entriesInCommon();
}
@Override public SortedMap<K, V> entriesOnlyOnLeft() {
return (SortedMap<K, V>) super.entriesOnlyOnLeft();
}
@Override public SortedMap<K, V> entriesOnlyOnRight() {
return (SortedMap<K, V>) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code
* Ordering.natural()}. This method is an abomination of generics; the only
* purpose of this method is to contain the ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static <E> Comparator<? super E> orNaturalOrder(
@Nullable Comparator<? super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator<E>) Ordering.natural();
}
/**
* Returns a live {@link Map} view whose keys are the contents of {@code set}
* and whose values are computed on demand using {@code function}. To get an
* immutable <i>copy</i> instead, use {@link #toMap(Iterable, Function)}.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map
* does not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also
* of type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> Map<K, V> asMap(
Set<K> set, Function<? super K, V> function) {
if (set instanceof SortedSet) {
return asMap((SortedSet<K>) set, function);
} else {
return new AsMapView<K, V>(set, function);
}
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set
* according to the specified function.
*
* <p>Specifically, for each {@code k} in the backing set, the returned map
* has an entry mapping {@code k} to {@code function.apply(k)}. The {@code
* keySet}, {@code values}, and {@code entrySet} views of the returned map
* iterate in the same order as the backing set.
*
* <p>Modifications to the backing set are read through to the returned map.
* The returned map supports removal operations if the backing set does.
* Removal operations write through to the backing set. The returned map does
* not support put operations.
*
* <p><b>Warning</b>: If the function rejects {@code null}, caution is
* required to make sure the set does not contain {@code null}, because the
* view cannot stop {@code null} from being added to the set.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
* type {@code K}. Using a key type for which this may not hold, such as
* {@code ArrayList}, may risk a {@code ClassCastException} when calling
* methods on the resulting map view.
*
* @since 14.0
*/
@Beta
public static <K, V> SortedMap<K, V> asMap(
SortedSet<K> set, Function<? super K, V> function) {
return Platform.mapsAsMapSortedSet(set, function);
}
static <K, V> SortedMap<K, V> asMapSortedIgnoreNavigable(SortedSet<K> set,
Function<? super K, V> function) {
return new SortedAsMapView<K, V>(set, function);
}
private static class AsMapView<K, V> extends ImprovedAbstractMap<K, V> {
private final Set<K> set;
final Function<? super K, V> function;
Set<K> backingSet() {
return set;
}
AsMapView(Set<K> set, Function<? super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set<K> createKeySet() {
return removeOnlySet(backingSet());
}
@Override
Collection<V> createValues() {
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@Nullable Object key) {
return backingSet().contains(key);
}
@Override
public V get(@Nullable Object key) {
if (Collections2.safeContains(backingSet(), key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public V remove(@Nullable Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet<K, V>() {
@Override
Map<K, V> map() {
return AsMapView.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return asMapEntryIterator(backingSet(), function);
}
};
}
}
static <K, V> Iterator<Entry<K, V>> asMapEntryIterator(
Set<K> set, final Function<? super K, V> function) {
return new TransformedIterator<K, Entry<K,V>>(set.iterator()) {
@Override
Entry<K, V> transform(final K key) {
return immutableEntry(key, function.apply(key));
}
};
}
private static class SortedAsMapView<K, V> extends AsMapView<K, V>
implements SortedMap<K, V> {
SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
super(set, function);
}
@Override
SortedSet<K> backingSet() {
return (SortedSet<K>) super.backingSet();
}
@Override
public Comparator<? super K> comparator() {
return backingSet().comparator();
}
@Override
public Set<K> keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap<K, V> headMap(K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap<K, V> tailMap(K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
public K firstKey() {
return backingSet().first();
}
@Override
public K lastKey() {
return backingSet().last();
}
}
private static <E> Set<E> removeOnlySet(final Set<E> set) {
return new ForwardingSet<E>() {
@Override
protected Set<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) {
return new ForwardingSortedSet<E>() {
@Override
protected SortedSet<E> delegate() {
return set;
}
@Override
public boolean add(E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet<E> headSet(E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code
* keys} and whose value for each key was computed by {@code valueFunction}.
* The map's iteration order is the order of the first appearance of each key
* in {@code keys}.
*
* <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of
* a copy using {@link Maps#asMap(Set, Function)}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys,
Function<? super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code
* keys} and whose value for each key was computed by {@code valueFunction}.
* The map's iteration order is the order of the first appearance of each key
* in {@code keys}.
*
* @throws NullPointerException if any element of {@code keys} is
* {@code null}, or if {@code valueFunction} produces {@code null}
* for any key
* @since 14.0
*/
@Beta
public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys,
Function<? super K, V> valueFunction) {
checkNotNull(valueFunction);
// Using LHM instead of a builder so as not to fail on duplicate keys
Map<K, V> builder = newLinkedHashMap();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
return ImmutableMap.copyOf(builder);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) {
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns an immutable map for which the {@link Map#values} are the given
* elements in the given order, and each key is the product of invoking a
* supplied function on its corresponding value.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code
* keyFunction} on each value in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same
* key for more than one value in the input collection
* @throws NullPointerException if any elements of {@code values} is null, or
* if {@code keyFunction} produces {@code null} for any value
* @since 10.0
*/
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
/**
* Returns an immutable map entry with the specified key and value. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
*
* <p>The returned entry is serializable.
*
* @param key the key to be associated with the returned entry
* @param value the value to be associated with the returned entry
*/
@GwtCompatible(serializable = true)
public static <K, V> Entry<K, V> immutableEntry(
@Nullable K key, @Nullable V value) {
return new ImmutableEntry<K, V>(key, value);
}
/**
* Returns an unmodifiable view of the specified set of entries. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException},
* as do any operations that would modify the returned set.
*
* @param entrySet the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
static <K, V> Set<Entry<K, V>> unmodifiableEntrySet(
Set<Entry<K, V>> entrySet) {
return new UnmodifiableEntrySet<K, V>(
Collections.unmodifiableSet(entrySet));
}
/**
* Returns an unmodifiable view of the specified map entry. The {@link
* Entry#setValue} operation throws an {@link UnsupportedOperationException}.
* This also has the side-effect of redefining {@code equals} to comply with
* the Entry contract, to avoid a possible nefarious implementation of equals.
*
* @param entry the entry for which to return an unmodifiable view
* @return an unmodifiable view of the entry
*/
static <K, V> Entry<K, V> unmodifiableEntry(final Entry<? extends K, ? extends V> entry) {
checkNotNull(entry);
return new AbstractMapEntry<K, V>() {
@Override public K getKey() {
return entry.getKey();
}
@Override public V getValue() {
return entry.getValue();
}
};
}
/** @see Multimaps#unmodifiableEntries */
static class UnmodifiableEntries<K, V>
extends ForwardingCollection<Entry<K, V>> {
private final Collection<Entry<K, V>> entries;
UnmodifiableEntries(Collection<Entry<K, V>> entries) {
this.entries = entries;
}
@Override protected Collection<Entry<K, V>> delegate() {
return entries;
}
@Override public Iterator<Entry<K, V>> iterator() {
final Iterator<Entry<K, V>> delegate = super.iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override public Entry<K, V> next() {
return unmodifiableEntry(delegate.next());
}
};
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public Object[] toArray() {
return standardToArray();
}
@Override public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
}
/** @see Maps#unmodifiableEntrySet(Set) */
static class UnmodifiableEntrySet<K, V>
extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
super(entries);
}
// See java.util.Collections.UnmodifiableEntrySet for details on attacks.
@Override public boolean equals(@Nullable Object object) {
return Sets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(this);
}
}
/**
* Returns a synchronized (thread-safe) bimap backed by the specified bimap.
* In order to guarantee serial access, it is critical that <b>all</b> access
* to the backing bimap is accomplished through the returned bimap.
*
* <p>It is imperative that the user manually synchronize on the returned map
* when accessing any of its collection views: <pre> {@code
*
* BiMap<Long, String> map = Maps.synchronizedBiMap(
* HashBiMap.<Long, String>create());
* ...
* Set<Long> set = map.keySet(); // Needn't be in synchronized block
* ...
* synchronized (map) { // Synchronizing on map, not set!
* Iterator<Long> it = set.iterator(); // Must be in synchronized block
* while (it.hasNext()) {
* foo(it.next());
* }
* }}</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap to be wrapped in a synchronized view
* @return a sychronized view of the specified bimap
*/
public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
return Synchronized.biMap(bimap, null);
}
/**
* Returns an unmodifiable view of the specified bimap. This method allows
* modules to provide users with "read-only" access to internal bimaps. Query
* operations on the returned bimap "read through" to the specified bimap, and
* attempts to modify the returned map, whether direct or via its collection
* views, result in an {@code UnsupportedOperationException}.
*
* <p>The returned bimap will be serializable if the specified bimap is
* serializable.
*
* @param bimap the bimap for which an unmodifiable view is to be returned
* @return an unmodifiable view of the specified bimap
*/
public static <K, V> BiMap<K, V> unmodifiableBiMap(
BiMap<? extends K, ? extends V> bimap) {
return new UnmodifiableBiMap<K, V>(bimap, null);
}
/** @see Maps#unmodifiableBiMap(BiMap) */
private static class UnmodifiableBiMap<K, V>
extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
final Map<K, V> unmodifiableMap;
final BiMap<? extends K, ? extends V> delegate;
BiMap<V, K> inverse;
transient Set<V> values;
UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate,
@Nullable BiMap<V, K> inverse) {
unmodifiableMap = Collections.unmodifiableMap(delegate);
this.delegate = delegate;
this.inverse = inverse;
}
@Override protected Map<K, V> delegate() {
return unmodifiableMap;
}
@Override
public V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public BiMap<V, K> inverse() {
BiMap<V, K> result = inverse;
return (result == null)
? inverse = new UnmodifiableBiMap<V, K>(delegate.inverse(), this)
: result;
}
@Override public Set<V> values() {
Set<V> result = values;
return (result == null)
? values = Collections.unmodifiableSet(delegate.values())
: result;
}
private static final long serialVersionUID = 0;
}
/**
* Returns a view of a map where each value is transformed by a function. All
* other properties of the map, such as iteration order, are left intact. For
* example, the code: <pre> {@code
*
* Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* Map<String, Double> transformed = Maps.transformValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*/
public static <K, V1, V2> Map<K, V2> transformValues(
Map<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a sorted map where each value is transformed by a
* function. All other properties of the map, such as iteration order, are
* left intact. For example, the code: <pre> {@code
*
* SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* SortedMap<String, Double> transformed =
* Maps.transformSortedValues(map, sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=2.0, b=3.0}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys, and even
* null values provided that the function is capable of accepting null input.
* The transformed map might contain null values, if the function sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned map to be a view, but it means that the function will be
* applied many times for bulk operations like {@link Map#containsValue} and
* {@code Map.toString()}. For this to perform well, {@code function} should
* be fast. To avoid lazy evaluation when the returned map doesn't need to be
* a view, copy the returned map into a new map of your choosing.
*
* @since 11.0
*/
public static <K, V1, V2> SortedMap<K, V2> transformValues(
SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
return transformEntries(fromMap, asEntryTransformer(function));
}
/**
* Returns a view of a map whose values are derived from the original map's
* entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "no" + key;
* }
* };
* Map<String, String> transformed =
* Maps.transformEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {verbose=verbose, sort=nosort}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 7.0
*/
public static <K, V1, V2> Map<K, V2> transformEntries(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
if (fromMap instanceof SortedMap) {
return transformEntries((SortedMap<K, V1>) fromMap, transformer);
}
return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer);
}
/**
* Returns a view of a sorted map whose values are derived from the original
* sorted map's entries. In contrast to {@link #transformValues}, this
* method's entry-transformation logic may depend on the key as well as the
* value.
*
* <p>All other properties of the transformed map, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* Map<String, Boolean> options =
* ImmutableSortedMap.of("verbose", true, "sort", false);
* EntryTransformer<String, Boolean, String> flagPrefixer =
* new EntryTransformer<String, Boolean, String>() {
* public String transformEntry(String key, Boolean value) {
* return value ? key : "yes" + key;
* }
* };
* SortedMap<String, String> transformed =
* LabsMaps.transformSortedEntries(options, flagPrefixer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {sort=yessort, verbose=verbose}}.
*
* <p>Changes in the underlying map are reflected in this view. Conversely,
* this view supports removal operations, and these are reflected in the
* underlying map.
*
* <p>It's acceptable for the underlying map to contain null keys and null
* values provided that the transformer is capable of accepting null inputs.
* The transformed map might contain null values if the transformer sometimes
* gives a null result.
*
* <p>The returned map is not thread-safe or serializable, even if the
* underlying map is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned map to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Map#containsValue} and {@link Object#toString}. For this to perform well,
* {@code transformer} should be fast. To avoid lazy evaluation when the
* returned map doesn't need to be a view, copy the returned map into a new
* map of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed map.
*
* @since 11.0
*/
public static <K, V1, V2> SortedMap<K, V2> transformEntries(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return Platform.mapsTransformEntriesSortedMap(fromMap, transformer);
}
static <K, V1, V2> SortedMap<K, V2> transformEntriesIgnoreNavigable(
SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesSortedMap<K, V1, V2>(fromMap, transformer);
}
/**
* A transformation of the value of a key-value pair, using both key and value
* as inputs. To apply the transformation to a map, use
* {@link Maps#transformEntries(Map, EntryTransformer)}.
*
* @param <K> the key type of the input and output entries
* @param <V1> the value type of the input entry
* @param <V2> the value type of the output entry
* @since 7.0
*/
public interface EntryTransformer<K, V1, V2> {
/**
* Determines an output value based on a key-value pair. This method is
* <i>generally expected</i>, but not absolutely required, to have the
* following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is,
* {@link Objects#equal Objects.equal}{@code (k1, k2) &&}
* {@link Objects#equal}{@code (v1, v2)} implies that {@code
* Objects.equal(transformer.transform(k1, v1),
* transformer.transform(k2, v2))}.
* </ul>
*
* @throws NullPointerException if the key or value is null and this
* transformer does not accept null arguments
*/
V2 transformEntry(@Nullable K key, @Nullable V1 value);
}
/**
* Views a function as an entry transformer that ignores the entry key.
*/
static <K, V1, V2> EntryTransformer<K, V1, V2>
asEntryTransformer(final Function<? super V1, V2> function) {
checkNotNull(function);
return new EntryTransformer<K, V1, V2>() {
@Override
public V2 transformEntry(K key, V1 value) {
return function.apply(value);
}
};
}
static <K, V1, V2> Function<V1, V2> asValueToValueFunction(
final EntryTransformer<? super K, V1, V2> transformer, final K key) {
checkNotNull(transformer);
return new Function<V1, V2>() {
@Override
public V2 apply(@Nullable V1 v1) {
return transformer.transformEntry(key, v1);
}
};
}
/**
* Views an entry transformer as a function from {@code Entry} to values.
*/
static <K, V1, V2> Function<Entry<K, V1>, V2> asEntryToValueFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, V2>() {
@Override
public V2 apply(Entry<K, V1> entry) {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/**
* Returns a view of an entry transformed by the specified transformer.
*/
static <V2, K, V1> Entry<K, V2> transformEntry(
final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
checkNotNull(transformer);
checkNotNull(entry);
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return transformer.transformEntry(entry.getKey(), entry.getValue());
}
};
}
/**
* Views an entry transformer as a function from entries to entries.
*/
static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
final EntryTransformer<? super K, ? super V1, V2> transformer) {
checkNotNull(transformer);
return new Function<Entry<K, V1>, Entry<K, V2>>() {
@Override
public Entry<K, V2> apply(final Entry<K, V1> entry) {
return transformEntry(transformer, entry);
}
};
}
static class TransformedEntriesMap<K, V1, V2>
extends ImprovedAbstractMap<K, V2> {
final Map<K, V1> fromMap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMap(
Map<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMap = checkNotNull(fromMap);
this.transformer = checkNotNull(transformer);
}
@Override public int size() {
return fromMap.size();
}
@Override public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 get(Object key) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key))
? transformer.transformEntry((K) key, value)
: null;
}
// safe as long as the user followed the <b>Warning</b> in the javadoc
@SuppressWarnings("unchecked")
@Override public V2 remove(Object key) {
return fromMap.containsKey(key)
? transformer.transformEntry((K) key, fromMap.remove(key))
: null;
}
@Override public void clear() {
fromMap.clear();
}
@Override public Set<K> keySet() {
return fromMap.keySet();
}
@Override
protected Set<Entry<K, V2>> createEntrySet() {
return new EntrySet<K, V2>() {
@Override Map<K, V2> map() {
return TransformedEntriesMap.this;
}
@Override public Iterator<Entry<K, V2>> iterator() {
return Iterators.transform(fromMap.entrySet().iterator(),
Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
};
}
}
static class TransformedEntriesSortedMap<K, V1, V2>
extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
protected SortedMap<K, V1> fromMap() {
return (SortedMap<K, V1>) fromMap;
}
TransformedEntriesSortedMap(SortedMap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMap, transformer);
}
@Override public Comparator<? super K> comparator() {
return fromMap().comparator();
}
@Override public K firstKey() {
return fromMap().firstKey();
}
@Override public SortedMap<K, V2> headMap(K toKey) {
return transformEntries(fromMap().headMap(toKey), transformer);
}
@Override public K lastKey() {
return fromMap().lastKey();
}
@Override public SortedMap<K, V2> subMap(K fromKey, K toKey) {
return transformEntries(
fromMap().subMap(fromKey, toKey), transformer);
}
@Override public SortedMap<K, V2> tailMap(K fromKey) {
return transformEntries(fromMap().tailMap(fromKey), transformer);
}
}
static <K> Predicate<Entry<K, ?>> keyPredicateOnEntries(Predicate<? super K> keyPredicate) {
return compose(keyPredicate, Maps.<K>keyFunction());
}
static <V> Predicate<Entry<?, V>> valuePredicateOnEntries(Predicate<? super V> valuePredicate) {
return compose(valuePredicate, Maps.<V>valueFunction());
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterKeys(
Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SortedMap) {
return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate);
} else if (unfiltered instanceof BiMap) {
return filterKeys((BiMap<K, V>) unfiltered, keyPredicate);
}
checkNotNull(keyPredicate);
Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredKeyMap<K, V>(
checkNotNull(unfiltered), keyPredicate, entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* keys satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a key that
* doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterKeys(
SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
// TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better
// performance.
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
* The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the
* bimap and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code
* put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterKeys(
BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
checkNotNull(keyPredicate);
return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*/
public static <K, V> Map<K, V> filterValues(
Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
if (unfiltered instanceof SortedMap) {
return filterValues((SortedMap<K, V>) unfiltered, valuePredicate);
} else if (unfiltered instanceof BiMap) {
return filterValues((BiMap<K, V>) unfiltered, valuePredicate);
}
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} whose
* values satisfy a predicate. The returned map is a live view of {@code
* unfiltered}; changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a value
* that doesn't satisfy the predicate, the map's {@code put()}, {@code
* putAll()}, and {@link Entry#setValue} methods throw an {@link
* IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings whose values satisfy the
* filter will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterValues(
SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a
* predicate. The returned bimap is a live view of {@code unfiltered}; changes to one affect the
* other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the
* bimap and its views. When given a value that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
* IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method
* that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the
* predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
* the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
* needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterValues(
BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a map containing the mappings in {@code unfiltered} that satisfy a
* predicate. The returned map is a live view of {@code unfiltered}; changes
* to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*/
public static <K, V> Map<K, V> filterEntries(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
if (unfiltered instanceof SortedMap) {
return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate);
} else if (unfiltered instanceof BiMap) {
return filterEntries((BiMap<K, V>) unfiltered, entryPredicate);
}
checkNotNull(entryPredicate);
return (unfiltered instanceof AbstractFilteredMap)
? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a sorted map containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned map is a live view of {@code unfiltered};
* changes to one affect the other.
*
* <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code
* values()} views have iterators that don't support {@code remove()}, but all
* other methods are supported by the map and its views. When given a
* key/value pair that doesn't satisfy the predicate, the map's {@code put()}
* and {@code putAll()} methods throw an {@link IllegalArgumentException}.
* Similarly, the map's entries have a {@link Entry#setValue} method that
* throws an {@link IllegalArgumentException} when the existing key and the
* provided value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called
* on the filtered map or its views, only mappings that satisfy the filter
* will be removed from the underlying map.
*
* <p>The returned map isn't threadsafe or serializable, even if {@code
* unfiltered} is.
*
* <p>Many of the filtered map's methods, such as {@code size()},
* iterate across every key/value mapping in the underlying map and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered map and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K, V> SortedMap<K, V> filterEntries(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
return Platform.mapsFilterSortedMap(unfiltered, entryPredicate);
}
static <K, V> SortedMap<K, V> filterSortedIgnoreNavigable(
SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntrySortedMap)
? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
* returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
* iterators that don't support {@code remove()}, but all other methods are supported by the bimap
* and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
* {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an
* {@link IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue}
* method that throws an {@link IllegalArgumentException} when the existing key and the provided
* value don't satisfy the predicate.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
* bimap or its views, only mappings that satisfy the filter will be removed from the underlying
* bimap.
*
* <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
*
* <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every
* key/value mapping in the underlying bimap and determine which satisfy the filter. When a live
* view is <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as
* documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> BiMap<K, V> filterEntries(
BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(unfiltered);
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredEntryBiMap)
? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate);
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
return new FilteredEntryMap<K, V>(map.unfiltered,
Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
}
private abstract static class AbstractFilteredMap<K, V>
extends ImprovedAbstractMap<K, V> {
final Map<K, V> unfiltered;
final Predicate<? super Entry<K, V>> predicate;
AbstractFilteredMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
this.unfiltered = unfiltered;
this.predicate = predicate;
}
boolean apply(@Nullable Object key, @Nullable V value) {
// This method is called only when the key is in the map, implying that
// key is a K.
@SuppressWarnings("unchecked")
K k = (K) key;
return predicate.apply(Maps.immutableEntry(k, value));
}
@Override public V put(K key, V value) {
checkArgument(apply(key, value));
return unfiltered.put(key, value);
}
@Override public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
checkArgument(apply(entry.getKey(), entry.getValue()));
}
unfiltered.putAll(map);
}
@Override public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
}
@Override public V get(Object key) {
V value = unfiltered.get(key);
return ((value != null) && apply(key, value)) ? value : null;
}
@Override public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override public V remove(Object key) {
return containsKey(key) ? unfiltered.remove(key) : null;
}
@Override
Collection<V> createValues() {
return new FilteredMapValues<K, V>(this, unfiltered, predicate);
}
}
private static final class FilteredMapValues<K, V> extends Maps.Values<K, V> {
Map<K, V> unfiltered;
Predicate<? super Entry<K, V>> predicate;
FilteredMapValues(Map<K, V> filteredMap, Map<K, V> unfiltered,
Predicate<? super Entry<K, V>> predicate) {
super(filteredMap);
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override public boolean remove(Object o) {
return Iterables.removeFirstMatching(unfiltered.entrySet(),
Predicates.<Entry<K, V>>and(predicate, Maps.<V>valuePredicateOnEntries(equalTo(o))))
!= null;
}
private boolean removeIf(Predicate<? super V> valuePredicate) {
return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and(
predicate, Maps.<V>valuePredicateOnEntries(valuePredicate)));
}
@Override public boolean removeAll(Collection<?> collection) {
return removeIf(in(collection));
}
@Override public boolean retainAll(Collection<?> collection) {
return removeIf(not(in(collection)));
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> {
Predicate<? super K> keyPredicate;
FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
this.keyPredicate = keyPredicate;
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
Set<K> createKeySet() {
return Sets.filter(unfiltered.keySet(), keyPredicate);
}
// The cast is called only when the key is in the unfiltered map, implying
// that key is a K.
@Override
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
}
}
static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> {
/**
* Entries in this set satisfy the predicate, but they don't validate the
* input to {@code Entry.setValue()}.
*/
final Set<Entry<K, V>> filteredEntrySet;
FilteredEntryMap(
Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new EntrySet();
}
private class EntrySet extends ForwardingSet<Entry<K, V>> {
@Override protected Set<Entry<K, V>> delegate() {
return filteredEntrySet;
}
@Override public Iterator<Entry<K, V>> iterator() {
return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
@Override
Entry<K, V> transform(final Entry<K, V> entry) {
return new ForwardingMapEntry<K, V>() {
@Override
protected Entry<K, V> delegate() {
return entry;
}
@Override
public V setValue(V newValue) {
checkArgument(apply(getKey(), newValue));
return super.setValue(newValue);
}
};
}
};
}
}
@Override
Set<K> createKeySet() {
return new KeySet();
}
class KeySet extends Maps.KeySet<K, V> {
KeySet() {
super(FilteredEntryMap.this);
}
@Override public boolean remove(Object o) {
if (containsKey(o)) {
unfiltered.remove(o);
return true;
}
return false;
}
private boolean removeIf(Predicate<? super K> keyPredicate) {
return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and(
predicate, Maps.<K>keyPredicateOnEntries(keyPredicate)));
}
@Override
public boolean removeAll(Collection<?> c) {
return removeIf(in(c));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeIf(not(in(c)));
}
@Override public Object[] toArray() {
// creating an ArrayList so filtering happens once
return Lists.newArrayList(iterator()).toArray();
}
@Override public <T> T[] toArray(T[] array) {
return Lists.newArrayList(iterator()).toArray(array);
}
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered sorted map.
*/
private static <K, V> SortedMap<K, V> filterFiltered(
FilteredEntrySortedMap<K, V> map,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(map.predicate, entryPredicate);
return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate);
}
private static class FilteredEntrySortedMap<K, V>
extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
FilteredEntrySortedMap(SortedMap<K, V> unfiltered,
Predicate<? super Entry<K, V>> entryPredicate) {
super(unfiltered, entryPredicate);
}
SortedMap<K, V> sortedMap() {
return (SortedMap<K, V>) unfiltered;
}
@Override public SortedSet<K> keySet() {
return (SortedSet<K>) super.keySet();
}
@Override
SortedSet<K> createKeySet() {
return new SortedKeySet();
}
class SortedKeySet extends KeySet implements SortedSet<K> {
@Override
public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return (SortedSet<K>) subMap(fromElement, toElement).keySet();
}
@Override
public SortedSet<K> headSet(K toElement) {
return (SortedSet<K>) headMap(toElement).keySet();
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return (SortedSet<K>) tailMap(fromElement).keySet();
}
@Override
public K first() {
return firstKey();
}
@Override
public K last() {
return lastKey();
}
}
@Override public Comparator<? super K> comparator() {
return sortedMap().comparator();
}
@Override public K firstKey() {
// correctly throws NoSuchElementException when filtered map is empty.
return keySet().iterator().next();
}
@Override public K lastKey() {
SortedMap<K, V> headMap = sortedMap();
while (true) {
// correctly throws NoSuchElementException when filtered map is empty.
K key = headMap.lastKey();
if (apply(key, unfiltered.get(key))) {
return key;
}
headMap = sortedMap().headMap(key);
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate);
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().subMap(fromKey, toKey), predicate);
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
return new FilteredEntrySortedMap<K, V>(
sortedMap().tailMap(fromKey), predicate);
}
}
/**
* Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when
* filtering a filtered map.
*/
private static <K, V> BiMap<K, V> filterFiltered(
FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate);
return new FilteredEntryBiMap<K, V>(map.unfiltered(), predicate);
}
static final class FilteredEntryBiMap<K, V> extends FilteredEntryMap<K, V>
implements BiMap<K, V> {
private final BiMap<V, K> inverse;
private static <K, V> Predicate<Entry<V, K>> inversePredicate(
final Predicate<? super Entry<K, V>> forwardPredicate) {
return new Predicate<Entry<V, K>>() {
@Override
public boolean apply(Entry<V, K> input) {
return forwardPredicate.apply(
Maps.immutableEntry(input.getValue(), input.getKey()));
}
};
}
FilteredEntryBiMap(BiMap<K, V> delegate,
Predicate<? super Entry<K, V>> predicate) {
super(delegate, predicate);
this.inverse = new FilteredEntryBiMap<V, K>(
delegate.inverse(), inversePredicate(predicate), this);
}
private FilteredEntryBiMap(
BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate,
BiMap<V, K> inverse) {
super(delegate, predicate);
this.inverse = inverse;
}
BiMap<K, V> unfiltered() {
return (BiMap<K, V>) unfiltered;
}
@Override
public V forcePut(@Nullable K key, @Nullable V value) {
checkArgument(apply(key, value));
return unfiltered().forcePut(key, value);
}
@Override
public BiMap<V, K> inverse() {
return inverse;
}
@Override
public Set<V> values() {
return inverse.keySet();
}
}
@Nullable private static <K, V> Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, V> entry) {
return (entry == null) ? null : Maps.unmodifiableEntry(entry);
}
/**
* {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code
* entrySet().isEmpty()} instead of {@code size() == 0} to speed up
* implementations where {@code size()} is O(n), and it delegates the {@code
* isEmpty()} methods of its key set and value collection to this
* implementation.
*/
@GwtCompatible
abstract static class ImprovedAbstractMap<K, V> extends AbstractMap<K, V> {
/**
* Creates the entry set to be returned by {@link #entrySet()}. This method
* is invoked at most once on a given map, at the time when {@code entrySet}
* is first called.
*/
abstract Set<Entry<K, V>> createEntrySet();
private transient Set<Entry<K, V>> entrySet;
@Override public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
}
private transient Set<K> keySet;
@Override public Set<K> keySet() {
Set<K> result = keySet;
return (result == null) ? keySet = createKeySet() : result;
}
Set<K> createKeySet() {
return new KeySet<K, V>(this);
}
private transient Collection<V> values;
@Override public Collection<V> values() {
Collection<V> result = values;
return (result == null) ? values = createValues() : result;
}
Collection<V> createValues() {
return new Values<K, V>(this);
}
}
/**
* Delegates to {@link Map#get}. Returns {@code null} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static <V> V safeGet(Map<?, V> map, @Nullable Object key) {
checkNotNull(map);
try {
return map.get(key);
} catch (ClassCastException e) {
return null;
} catch (NullPointerException e) {
return null;
}
}
/**
* Delegates to {@link Map#containsKey}. Returns {@code false} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static boolean safeContainsKey(Map<?, ?> map, Object key) {
checkNotNull(map);
try {
return map.containsKey(key);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}
/**
* Delegates to {@link Map#remove}. Returns {@code null} on {@code
* ClassCastException} and {@code NullPointerException}.
*/
static <V> V safeRemove(Map<?, V> map, Object key) {
checkNotNull(map);
try {
return map.remove(key);
} catch (ClassCastException e) {
return null;
} catch (NullPointerException e) {
return null;
}
}
/**
* An admittedly inefficient implementation of {@link Map#containsKey}.
*/
static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) {
return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
}
/**
* An implementation of {@link Map#containsValue}.
*/
static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) {
return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
}
/**
* Implements {@code Collection.contains} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is the backing (delegate) collection, rather than
* the forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object that might be contained in {@code c}
* @return {@code true} if {@code c} contains {@code o}
*/
static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.contains(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* Implements {@code Collection.remove} safely for forwarding collections of
* map entries. If {@code o} is an instance of {@code Map.Entry}, it is
* wrapped using {@link #unmodifiableEntry} to protect against a possible
* nefarious equals method.
*
* <p>Note that {@code c} is backing (delegate) collection, rather than the
* forwarding collection.
*
* @param c the delegate (unwrapped) collection of map entries
* @param o the object to remove from {@code c}
* @return {@code true} if {@code c} was changed
*/
static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) {
if (!(o instanceof Entry)) {
return false;
}
return c.remove(unmodifiableEntry((Entry<?, ?>) o));
}
/**
* An implementation of {@link Map#equals}.
*/
static boolean equalsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
} else if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
static final MapJoiner STANDARD_JOINER =
Collections2.STANDARD_JOINER.withKeyValueSeparator("=");
/**
* An implementation of {@link Map#toString}.
*/
static String toStringImpl(Map<?, ?> map) {
StringBuilder sb
= Collections2.newStringBuilderForCollection(map.size()).append('{');
STANDARD_JOINER.appendTo(sb, map);
return sb.append('}').toString();
}
/**
* An implementation of {@link Map#putAll}.
*/
static <K, V> void putAllImpl(
Map<K, V> self, Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
self.put(entry.getKey(), entry.getValue());
}
}
static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> {
final Map<K, V> map;
KeySet(Map<K, V> map) {
this.map = checkNotNull(map);
}
Map<K, V> map() {
return map;
}
@Override public Iterator<K> iterator() {
return keyIterator(map().entrySet().iterator());
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(Object o) {
return map().containsKey(o);
}
@Override public boolean remove(Object o) {
if (contains(o)) {
map().remove(o);
return true;
}
return false;
}
@Override public void clear() {
map().clear();
}
}
@Nullable
static <K> K keyOrNull(@Nullable Entry<K, ?> entry) {
return (entry == null) ? null : entry.getKey();
}
@Nullable
static <V> V valueOrNull(@Nullable Entry<?, V> entry) {
return (entry == null) ? null : entry.getValue();
}
static class SortedKeySet<K, V> extends KeySet<K, V> implements SortedSet<K> {
SortedKeySet(SortedMap<K, V> map) {
super(map);
}
@Override
SortedMap<K, V> map() {
return (SortedMap<K, V>) super.map();
}
@Override
public Comparator<? super K> comparator() {
return map().comparator();
}
@Override
public SortedSet<K> subSet(K fromElement, K toElement) {
return new SortedKeySet<K, V>(map().subMap(fromElement, toElement));
}
@Override
public SortedSet<K> headSet(K toElement) {
return new SortedKeySet<K, V>(map().headMap(toElement));
}
@Override
public SortedSet<K> tailSet(K fromElement) {
return new SortedKeySet<K, V>(map().tailMap(fromElement));
}
@Override
public K first() {
return map().firstKey();
}
@Override
public K last() {
return map().lastKey();
}
}
static class Values<K, V> extends AbstractCollection<V> {
final Map<K, V> map;
Values(Map<K, V> map) {
this.map = checkNotNull(map);
}
final Map<K, V> map() {
return map;
}
@Override public Iterator<V> iterator() {
return valueIterator(map().entrySet().iterator());
}
@Override public boolean remove(Object o) {
try {
return super.remove(o);
} catch (UnsupportedOperationException e) {
for (Entry<K, V> entry : map().entrySet()) {
if (Objects.equal(o, entry.getValue())) {
map().remove(entry.getKey());
return true;
}
}
return false;
}
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRemove = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRemove.add(entry.getKey());
}
}
return map().keySet().removeAll(toRemove);
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
Set<K> toRetain = Sets.newHashSet();
for (Entry<K, V> entry : map().entrySet()) {
if (c.contains(entry.getValue())) {
toRetain.add(entry.getKey());
}
}
return map().keySet().retainAll(toRetain);
}
}
@Override public int size() {
return map().size();
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
return map().containsValue(o);
}
@Override public void clear() {
map().clear();
}
}
abstract static class EntrySet<K, V>
extends Sets.ImprovedAbstractSet<Entry<K, V>> {
abstract Map<K, V> map();
@Override public int size() {
return map().size();
}
@Override public void clear() {
map().clear();
}
@Override public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
V value = Maps.safeGet(map(), key);
return Objects.equal(value, entry.getValue())
&& (value != null || map().containsKey(key));
}
return false;
}
@Override public boolean isEmpty() {
return map().isEmpty();
}
@Override public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
return map().keySet().remove(entry.getKey());
}
return false;
}
@Override public boolean removeAll(Collection<?> c) {
try {
return super.removeAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
return Sets.removeAllImpl(this, c.iterator());
}
}
@Override public boolean retainAll(Collection<?> c) {
try {
return super.retainAll(checkNotNull(c));
} catch (UnsupportedOperationException e) {
// if the iterators don't support remove
Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size());
for (Object o : c) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
keys.add(entry.getKey());
}
}
return map().keySet().retainAll(keys);
}
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to object arrays.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class ObjectArrays {
static final Object[] EMPTY_ARRAY = new Object[0];
private ObjectArrays() {}
/**
* Returns a new array of the given length with the same type as a reference
* array.
*
* @param reference any array of the desired type
* @param length the length of the new array
*/
public static <T> T[] newArray(T[] reference, int length) {
return Platform.newArray(reference, length);
}
/**
* Returns a new array that prepends {@code element} to {@code array}.
*
* @param element the element to prepend to the front of {@code array}
* @param array the array of elements to append
* @return an array whose size is one larger than {@code array}, with
* {@code element} occupying the first position, and the
* elements of {@code array} occupying the remaining elements.
*/
public static <T> T[] concat(@Nullable T element, T[] array) {
T[] result = newArray(array, array.length + 1);
result[0] = element;
System.arraycopy(array, 0, result, 1, array.length);
return result;
}
/**
* Returns a new array that appends {@code element} to {@code array}.
*
* @param array the array of elements to prepend
* @param element the element to append to the end
* @return an array whose size is one larger than {@code array}, with
* the same contents as {@code array}, plus {@code element} occupying the
* last position.
*/
public static <T> T[] concat(T[] array, @Nullable T element) {
T[] result = arraysCopyOf(array, array.length + 1);
result[array.length] = element;
return result;
}
/** GWT safe version of Arrays.copyOf. */
static <T> T[] arraysCopyOf(T[] original, int newLength) {
T[] copy = newArray(original, newLength);
System.arraycopy(
original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
/**
* Returns an array containing all of the elements in the specified
* collection; the runtime type of the returned array is that of the specified
* array. If the collection fits in the specified array, it is returned
* therein. Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of the specified collection.
*
* <p>If the collection fits in the specified array with room to spare (i.e.,
* the array has more elements than the collection), the element in the array
* immediately following the end of the collection is set to {@code null}.
* This is useful in determining the length of the collection <i>only</i> if
* the caller knows that the collection does not contain any null elements.
*
* <p>This method returns the elements in the order they are returned by the
* collection's iterator.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
* @param array the array in which to place the collection elements
* @throws ArrayStoreException if the runtime type of the specified array is
* not a supertype of the runtime type of every element in the specified
* collection
*/
static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
int size = c.size();
if (array.length < size) {
array = newArray(array, size);
}
fillArray(c, array);
if (array.length > size) {
array[size] = null;
}
return array;
}
/**
* Implementation of {@link Collection#toArray(Object[])} for collections backed by an object
* array. the runtime type of the returned array is that of the specified array. If the collection
* fits in the specified array, it is returned therein. Otherwise, a new array is allocated with
* the runtime type of the specified array and the size of the specified collection.
*
* <p>If the collection fits in the specified array with room to spare (i.e., the array has more
* elements than the collection), the element in the array immediately following the end of the
* collection is set to {@code null}. This is useful in determining the length of the collection
* <i>only</i> if the caller knows that the collection does not contain any null elements.
*/
static <T> T[] toArrayImpl(Object[] src, int offset, int len, T[] dst) {
checkPositionIndexes(offset, offset + len, src.length);
if (dst.length < len) {
dst = newArray(dst, len);
} else if (dst.length > len) {
dst[len] = null;
}
System.arraycopy(src, offset, dst, 0, len);
return dst;
}
/**
* Returns an array containing all of the elements in the specified
* collection. This method returns the elements in the order they are returned
* by the collection's iterator. The returned array is "safe" in that no
* references to it are maintained by the collection. The caller is thus free
* to modify the returned array.
*
* <p>This method assumes that the collection size doesn't change while the
* method is running.
*
* <p>TODO(kevinb): support concurrently modified collections?
*
* @param c the collection for which to return an array of elements
*/
static Object[] toArrayImpl(Collection<?> c) {
return fillArray(c, new Object[c.size()]);
}
/**
* Returns a copy of the specified subrange of the specified array that is literally an Object[],
* and not e.g. a {@code String[]}.
*/
static Object[] copyAsObjectArray(Object[] elements, int offset, int length) {
checkPositionIndexes(offset, offset + length, elements.length);
if (length == 0) {
return EMPTY_ARRAY;
}
Object[] result = new Object[length];
System.arraycopy(elements, offset, result, 0, length);
return result;
}
private static Object[] fillArray(Iterable<?> elements, Object[] array) {
int i = 0;
for (Object element : elements) {
array[i++] = element;
}
return array;
}
/**
* Swaps {@code array[i]} with {@code array[j]}.
*/
static void swap(Object[] array, int i, int j) {
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
static Object[] checkElementsNotNull(Object... array) {
return checkElementsNotNull(array, array.length);
}
static Object[] checkElementsNotNull(Object[] array, int length) {
for (int i = 0; i < length; i++) {
checkElementNotNull(array[i], i);
}
return array;
}
// We do this instead of Preconditions.checkNotNull to save boxing and array
// creation cost.
static Object checkElementNotNull(Object element, int index) {
if (element == null) {
throw new NullPointerException("at index " + index);
}
return element;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* GWT emulated version of {@link ImmutableList}.
* TODO(cpovirk): more doc
*
* @author Hayward Chan
*/
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableList<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
static final ImmutableList<Object> EMPTY =
new RegularImmutableList<Object>(Collections.emptyList());
ImmutableList() {}
// Casting to any type is safe because the list will never hold any elements.
@SuppressWarnings("unchecked")
public static <E> ImmutableList<E> of() {
return (ImmutableList<E>) EMPTY;
}
public static <E> ImmutableList<E> of(E element) {
return new SingletonImmutableList<E>(element);
}
public static <E> ImmutableList<E> of(E e1, E e2) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2));
}
public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3));
}
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4));
}
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5));
}
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
return new RegularImmutableList<E>(
ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8, e9));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(
e1, e2, e3, e4, e5, e6, e7, e8, e9, e10));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(
e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11));
}
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11,
E e12, E... others) {
final int paramCount = 12;
Object[] array = new Object[paramCount + others.length];
arrayCopy(array, 0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12);
arrayCopy(array, paramCount, others);
return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(array));
}
private static void arrayCopy(Object[] dest, int pos, Object... source) {
System.arraycopy(source, 0, dest, pos, source.length);
}
public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
return (elements instanceof Collection)
? copyOf((Collection<? extends E>) elements)
: copyOf(elements.iterator());
}
public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) {
return copyFromCollection(Lists.newArrayList(elements));
}
public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableCollection) {
/*
* TODO: When given an ImmutableList that's a sublist, copy the referenced
* portion of the array into a new array to save space?
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableCollection<E> list = (ImmutableCollection<E>) elements;
return list.asList();
}
return copyFromCollection(elements);
}
public static <E> ImmutableList<E> copyOf(E[] elements) {
checkNotNull(elements); // eager for GWT
return copyOf(Arrays.asList(elements));
}
private static <E> ImmutableList<E> copyFromCollection(
Collection<? extends E> collection) {
Object[] elements = collection.toArray();
switch (elements.length) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // collection had only Es in it
ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
return list;
default:
return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(elements));
}
}
// Factory method that skips the null checks. Used only when the elements
// are guaranteed to be non-null.
static <E> ImmutableList<E> unsafeDelegateList(List<? extends E> list) {
switch (list.size()) {
case 0:
return of();
case 1:
return new SingletonImmutableList<E>(list.iterator().next());
default:
@SuppressWarnings("unchecked")
List<E> castedList = (List<E>) list;
return new RegularImmutableList<E>(castedList);
}
}
/**
* Views the array as an immutable list. The array must have only {@code E} elements.
*
* <p>The array must be internally created.
*/
@SuppressWarnings("unchecked") // caller is reponsible for getting this right
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
return unsafeDelegateList((List) Arrays.asList(elements));
}
private static <E> List<E> nullCheckedList(Object... array) {
for (int i = 0, len = array.length; i < len; i++) {
if (array[i] == null) {
throw new NullPointerException("at index " + i);
}
}
@SuppressWarnings("unchecked")
E[] castedArray = (E[]) array;
return Arrays.asList(castedArray);
}
@Override
public int indexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.indexOfImpl(this, object);
}
@Override
public int lastIndexOf(@Nullable Object object) {
return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object);
}
public final boolean addAll(int index, Collection<? extends E> newElements) {
throw new UnsupportedOperationException();
}
public final E set(int index, E element) {
throw new UnsupportedOperationException();
}
public final void add(int index, E element) {
throw new UnsupportedOperationException();
}
public final E remove(int index) {
throw new UnsupportedOperationException();
}
@Override public UnmodifiableIterator<E> iterator() {
return listIterator();
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
return unsafeDelegateList(Lists.subListImpl(this, fromIndex, toIndex));
}
@Override public UnmodifiableListIterator<E> listIterator() {
return listIterator(0);
}
@Override public UnmodifiableListIterator<E> listIterator(int index) {
return new AbstractIndexedListIterator<E>(size(), index) {
@Override
protected E get(int index) {
return ImmutableList.this.get(index);
}
};
}
@Override public ImmutableList<E> asList() {
return this;
}
@Override
public boolean equals(@Nullable Object obj) {
return Lists.equalsImpl(this, obj);
}
@Override
public int hashCode() {
return Lists.hashCodeImpl(this);
}
public ImmutableList<E> reverse() {
List<E> list = Lists.newArrayList(this);
Collections.reverse(list);
return unsafeDelegateList(list);
}
public static <E> Builder<E> builder() {
return new Builder<E>();
}
public static final class Builder<E> extends ImmutableCollection.Builder<E> {
private final ArrayList<E> contents;
public Builder() {
contents = Lists.newArrayList();
}
Builder(int capacity) {
contents = Lists.newArrayListWithCapacity(capacity);
}
@Override public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override public Builder<E> add(E... elements) {
checkNotNull(elements); // for GWT
super.add(elements);
return this;
}
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
@Override public ImmutableList<E> build() {
return copyOf(contents);
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.singletonList;
import java.util.List;
/**
* GWT emulated version of {@link SingletonImmutableList}.
*
* @author Hayward Chan
*/
final class SingletonImmutableList<E> extends ForwardingImmutableList<E> {
final transient List<E> delegate;
// This reference is used both by the custom field serializer, and by the
// GWT compiler to infer the elements of the lists that needs to be
// serialized.
E element;
SingletonImmutableList(E element) {
this.delegate = singletonList(checkNotNull(element));
this.element = element;
}
@Override List<E> delegateList() {
return delegate;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.annotation.Nullable;
/**
* This class contains static utility methods that operate on or return objects
* of type {@link Iterator}. Except as noted, each method has a corresponding
* {@link Iterable}-based method in the {@link Iterables} class.
*
* <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators
* produced in this class are <i>lazy</i>, which means that they only advance
* the backing iteration when absolutely necessary.
*
* <p>See the Guava User Guide section on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables">
* {@code Iterators}</a>.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Iterators {
private Iterators() {}
static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR
= new UnmodifiableListIterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
@Override
public boolean hasPrevious() {
return false;
}
@Override
public Object previous() {
throw new NoSuchElementException();
}
@Override
public int nextIndex() {
return 0;
}
@Override
public int previousIndex() {
return -1;
}
};
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* ImmutableSet#of()}.
*/
public static <T> UnmodifiableIterator<T> emptyIterator() {
return emptyListIterator();
}
/**
* Returns the empty iterator.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* ImmutableSet#of()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T> UnmodifiableListIterator<T> emptyListIterator() {
return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR;
}
private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR =
new Iterator<Object>() {
@Override public boolean hasNext() {
return false;
}
@Override public Object next() {
throw new NoSuchElementException();
}
@Override public void remove() {
throw new IllegalStateException();
}
};
/**
* Returns the empty {@code Iterator} that throws
* {@link IllegalStateException} instead of
* {@link UnsupportedOperationException} on a call to
* {@link Iterator#remove()}.
*/
// Casting to any type is safe since there are no actual elements.
@SuppressWarnings("unchecked")
static <T> Iterator<T> emptyModifiableIterator() {
return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR;
}
/** Returns an unmodifiable view of {@code iterator}. */
public static <T> UnmodifiableIterator<T> unmodifiableIterator(
final Iterator<T> iterator) {
checkNotNull(iterator);
if (iterator instanceof UnmodifiableIterator) {
return (UnmodifiableIterator<T>) iterator;
}
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator(
UnmodifiableIterator<T> iterator) {
return checkNotNull(iterator);
}
/**
* Returns the number of elements remaining in {@code iterator}. The iterator
* will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*/
public static int size(Iterator<?> iterator) {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
/**
* Returns {@code true} if {@code iterator} contains {@code element}.
*/
public static boolean contains(Iterator<?> iterator, @Nullable Object element) {
return any(iterator, equalTo(element));
}
/**
* Traverses an iterator and removes every element that belongs to the
* provided collection. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRemove the elements to remove
* @return {@code true} if any element was removed from {@code iterator}
*/
public static boolean removeAll(
Iterator<?> removeFrom, Collection<?> elementsToRemove) {
return removeIf(removeFrom, in(elementsToRemove));
}
/**
* Removes every element that satisfies the provided predicate from the
* iterator. The iterator will be left exhausted: its {@code hasNext()}
* method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param predicate a predicate that determines whether an element should
* be removed
* @return {@code true} if any elements were removed from the iterator
* @since 2.0
*/
public static <T> boolean removeIf(
Iterator<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
boolean modified = false;
while (removeFrom.hasNext()) {
if (predicate.apply(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
/**
* Traverses an iterator and removes every element that does not belong to the
* provided collection. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @param removeFrom the iterator to (potentially) remove elements from
* @param elementsToRetain the elements to retain
* @return {@code true} if any element was removed from {@code iterator}
*/
public static boolean retainAll(
Iterator<?> removeFrom, Collection<?> elementsToRetain) {
return removeIf(removeFrom, not(in(elementsToRetain)));
}
/**
* Determines whether two iterators contain equal elements in the same order.
* More specifically, this method returns {@code true} if {@code iterator1}
* and {@code iterator2} contain the same number of elements and every element
* of {@code iterator1} is equal to the corresponding element of
* {@code iterator2}.
*
* <p>Note that this will modify the supplied iterators, since they will have
* been advanced some number of elements forward.
*/
public static boolean elementsEqual(
Iterator<?> iterator1, Iterator<?> iterator2) {
while (iterator1.hasNext()) {
if (!iterator2.hasNext()) {
return false;
}
Object o1 = iterator1.next();
Object o2 = iterator2.next();
if (!Objects.equal(o1, o2)) {
return false;
}
}
return !iterator2.hasNext();
}
/**
* Returns a string representation of {@code iterator}, with the format
* {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*/
public static String toString(Iterator<?> iterator) {
return Collections2.STANDARD_JOINER
.appendTo(new StringBuilder().append('['), iterator)
.append(']')
.toString();
}
/**
* Returns the single element contained in {@code iterator}.
*
* @throws NoSuchElementException if the iterator is empty
* @throws IllegalArgumentException if the iterator contains multiple
* elements. The state of the iterator is unspecified.
*/
public static <T> T getOnlyElement(Iterator<T> iterator) {
T first = iterator.next();
if (!iterator.hasNext()) {
return first;
}
StringBuilder sb = new StringBuilder();
sb.append("expected one element but was: <" + first);
for (int i = 0; i < 4 && iterator.hasNext(); i++) {
sb.append(", " + iterator.next());
}
if (iterator.hasNext()) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
/**
* Returns the single element contained in {@code iterator}, or {@code
* defaultValue} if the iterator is empty.
*
* @throws IllegalArgumentException if the iterator contains multiple
* elements. The state of the iterator is unspecified.
*/
@Nullable
public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
}
/**
* Adds all elements in {@code iterator} to {@code collection}. The iterator
* will be left exhausted: its {@code hasNext()} method will return
* {@code false}.
*
* @return {@code true} if {@code collection} was modified as a result of this
* operation
*/
public static <T> boolean addAll(
Collection<T> addTo, Iterator<? extends T> iterator) {
checkNotNull(addTo);
checkNotNull(iterator);
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
/**
* Returns the number of elements in the specified iterator that equal the
* specified object. The iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}.
*
* @see Collections#frequency
*/
public static int frequency(Iterator<?> iterator, @Nullable Object element) {
return size(filter(iterator, equalTo(element)));
}
/**
* Returns an iterator that cycles indefinitely over the elements of {@code
* iterable}.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator
* does. After {@code remove()} is called, subsequent cycles omit the removed
* element, which is no longer in {@code iterable}. The iterator's
* {@code hasNext()} method returns {@code true} until {@code iterable} is
* empty.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*/
public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
checkNotNull(iterable);
return new Iterator<T>() {
Iterator<T> iterator = emptyIterator();
Iterator<T> removeFrom;
@Override
public boolean hasNext() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.hasNext();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
removeFrom = iterator;
return iterator.next();
}
@Override
public void remove() {
checkRemove(removeFrom != null);
removeFrom.remove();
removeFrom = null;
}
};
}
/**
* Returns an iterator that cycles indefinitely over the provided elements.
*
* <p>The returned iterator supports {@code remove()}. After {@code remove()}
* is called, subsequent cycles omit the removed
* element, but {@code elements} does not change. The iterator's
* {@code hasNext()} method returns {@code true} until all of the original
* elements have been removed.
*
* <p><b>Warning:</b> Typical uses of the resulting iterator may produce an
* infinite loop. You should use an explicit {@code break} or be certain that
* you will eventually remove all the elements.
*/
public static <T> Iterator<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
}
/**
* Combines two iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}. The source iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b) {
return concat(ImmutableList.of(a, b).iterator());
}
/**
* Combines three iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}, followed by the elements in {@code c}. The source iterators
* are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b, Iterator<? extends T> c) {
return concat(ImmutableList.of(a, b, c).iterator());
}
/**
* Combines four iterators into a single iterator. The returned iterator
* iterates across the elements in {@code a}, followed by the elements in
* {@code b}, followed by the elements in {@code c}, followed by the elements
* in {@code d}. The source iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
public static <T> Iterator<T> concat(Iterator<? extends T> a,
Iterator<? extends T> b, Iterator<? extends T> c,
Iterator<? extends T> d) {
return concat(ImmutableList.of(a, b, c, d).iterator());
}
/**
* Combines multiple iterators into a single iterator. The returned iterator
* iterates across the elements of each iterator in {@code inputs}. The input
* iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*
* @throws NullPointerException if any of the provided iterators is null
*/
public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
return concat(ImmutableList.copyOf(inputs).iterator());
}
/**
* Combines multiple iterators into a single iterator. The returned iterator
* iterates across the elements of each iterator in {@code inputs}. The input
* iterators are not polled until necessary.
*
* <p>The returned iterator supports {@code remove()} when the corresponding
* input iterator supports it. The methods of the returned iterator may throw
* {@code NullPointerException} if any of the input iterators is null.
*
* <p><b>Note:</b> the current implementation is not suitable for nested
* concatenated iterators, i.e. the following should be avoided when in a loop:
* {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the
* resulting iterator has a cubic complexity to the depth of the nesting.
*/
public static <T> Iterator<T> concat(
final Iterator<? extends Iterator<? extends T>> inputs) {
checkNotNull(inputs);
return new Iterator<T>() {
Iterator<? extends T> current = emptyIterator();
Iterator<? extends T> removeFrom;
@Override
public boolean hasNext() {
// http://code.google.com/p/google-collections/issues/detail?id=151
// current.hasNext() might be relatively expensive, worth minimizing.
boolean currentHasNext;
// checkNotNull eager for GWT
// note: it must be here & not where 'current' is assigned,
// because otherwise we'll have called inputs.next() before throwing
// the first NPE, and the next time around we'll call inputs.next()
// again, incorrectly moving beyond the error.
while (!(currentHasNext = checkNotNull(current).hasNext())
&& inputs.hasNext()) {
current = inputs.next();
}
return currentHasNext;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
removeFrom = current;
return current.next();
}
@Override
public void remove() {
checkRemove(removeFrom != null);
removeFrom.remove();
removeFrom = null;
}
};
}
/**
* Divides an iterator into unmodifiable sublists of the given size (the final
* list may be smaller). For example, partitioning an iterator containing
* {@code [a, b, c, d, e]} with a partition size of 3 yields {@code
* [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of
* three and two elements, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition (the last may be smaller)
* @return an iterator of immutable lists containing the elements of {@code
* iterator} divided into partitions
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> UnmodifiableIterator<List<T>> partition(
Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, false);
}
/**
* Divides an iterator into unmodifiable sublists of the given size, padding
* the final iterator with null values if necessary. For example, partitioning
* an iterator containing {@code [a, b, c, d, e]} with a partition size of 3
* yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing
* two inner lists of three elements each, all in the original order.
*
* <p>The returned lists implement {@link java.util.RandomAccess}.
*
* @param iterator the iterator to return a partitioned view of
* @param size the desired size of each partition
* @return an iterator of immutable lists containing the elements of {@code
* iterator} divided into partitions (the final iterable may have
* trailing null elements)
* @throws IllegalArgumentException if {@code size} is nonpositive
*/
public static <T> UnmodifiableIterator<List<T>> paddedPartition(
Iterator<T> iterator, int size) {
return partitionImpl(iterator, size, true);
}
private static <T> UnmodifiableIterator<List<T>> partitionImpl(
final Iterator<T> iterator, final int size, final boolean pad) {
checkNotNull(iterator);
checkArgument(size > 0);
return new UnmodifiableIterator<List<T>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public List<T> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Object[] array = new Object[size];
int count = 0;
for (; count < size && iterator.hasNext(); count++) {
array[count] = iterator.next();
}
for (int i = count; i < size; i++) {
array[i] = null; // for GWT
}
@SuppressWarnings("unchecked") // we only put Ts in it
List<T> list = Collections.unmodifiableList(
(List<T>) Arrays.asList(array));
return (pad || count == size) ? list : list.subList(0, count);
}
};
}
/**
* Returns the elements of {@code unfiltered} that satisfy a predicate.
*/
public static <T> UnmodifiableIterator<T> filter(
final Iterator<T> unfiltered, final Predicate<? super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new AbstractIterator<T>() {
@Override protected T computeNext() {
while (unfiltered.hasNext()) {
T element = unfiltered.next();
if (predicate.apply(element)) {
return element;
}
}
return endOfData();
}
};
}
/**
* Returns {@code true} if one or more elements returned by {@code iterator}
* satisfy the given predicate.
*/
public static <T> boolean any(
Iterator<T> iterator, Predicate<? super T> predicate) {
return indexOf(iterator, predicate) != -1;
}
/**
* Returns {@code true} if every element returned by {@code iterator}
* satisfies the given predicate. If {@code iterator} is empty, {@code true}
* is returned.
*/
public static <T> boolean all(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate);
while (iterator.hasNext()) {
T element = iterator.next();
if (!predicate.apply(element)) {
return false;
}
}
return true;
}
/**
* Returns the first element in {@code iterator} that satisfies the given
* predicate; use this method only when such an element is known to exist. If
* no such element is found, the iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}. If it is possible that
* <i>no</i> element will match, use {@link #tryFind} or {@link
* #find(Iterator, Predicate, Object)} instead.
*
* @throws NoSuchElementException if no element in {@code iterator} matches
* the given predicate
*/
public static <T> T find(
Iterator<T> iterator, Predicate<? super T> predicate) {
return filter(iterator, predicate).next();
}
/**
* Returns the first element in {@code iterator} that satisfies the given
* predicate. If no such element is found, {@code defaultValue} will be
* returned from this method and the iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}. Note that this can
* usually be handled more naturally using {@code
* tryFind(iterator, predicate).or(defaultValue)}.
*
* @since 7.0
*/
@Nullable
public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate,
@Nullable T defaultValue) {
return getNext(filter(iterator, predicate), defaultValue);
}
/**
* Returns an {@link Optional} containing the first element in {@code
* iterator} that satisfies the given predicate, if such an element exists. If
* no such element is found, an empty {@link Optional} will be returned from
* this method and the iterator will be left exhausted: its {@code
* hasNext()} method will return {@code false}.
*
* <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code
* null}. If {@code null} is matched in {@code iterator}, a
* NullPointerException will be thrown.
*
* @since 11.0
*/
public static <T> Optional<T> tryFind(
Iterator<T> iterator, Predicate<? super T> predicate) {
UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate);
return filteredIterator.hasNext()
? Optional.of(filteredIterator.next())
: Optional.<T>absent();
}
/**
* Returns the index in {@code iterator} of the first element that satisfies
* the provided {@code predicate}, or {@code -1} if the Iterator has no such
* elements.
*
* <p>More formally, returns the lowest index {@code i} such that
* {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true},
* or {@code -1} if there is no such index.
*
* <p>If -1 is returned, the iterator will be left exhausted: its
* {@code hasNext()} method will return {@code false}. Otherwise,
* the iterator will be set to the element which satisfies the
* {@code predicate}.
*
* @since 2.0
*/
public static <T> int indexOf(
Iterator<T> iterator, Predicate<? super T> predicate) {
checkNotNull(predicate, "predicate");
for (int i = 0; iterator.hasNext(); i++) {
T current = iterator.next();
if (predicate.apply(current)) {
return i;
}
}
return -1;
}
/**
* Returns an iterator that applies {@code function} to each element of {@code
* fromIterator}.
*
* <p>The returned iterator supports {@code remove()} if the provided iterator
* does. After a successful {@code remove()} call, {@code fromIterator} no
* longer contains the corresponding element.
*/
public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator,
final Function<? super F, ? extends T> function) {
checkNotNull(function);
return new TransformedIterator<F, T>(fromIterator) {
@Override
T transform(F from) {
return function.apply(from);
}
};
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the
* element at the {@code position}th position.
*
* @param position position of the element to return
* @return the element at the specified position in {@code iterator}
* @throws IndexOutOfBoundsException if {@code position} is negative or
* greater than or equal to the number of elements remaining in
* {@code iterator}
*/
public static <T> T get(Iterator<T> iterator, int position) {
checkNonnegative(position);
int skipped = advance(iterator, position);
if (!iterator.hasNext()) {
throw new IndexOutOfBoundsException("position (" + position
+ ") must be less than the number of elements that remained ("
+ skipped + ")");
}
return iterator.next();
}
static void checkNonnegative(int position) {
if (position < 0) {
throw new IndexOutOfBoundsException("position (" + position
+ ") must not be negative");
}
}
/**
* Advances {@code iterator} {@code position + 1} times, returning the
* element at the {@code position}th position or {@code defaultValue}
* otherwise.
*
* @param position position of the element to return
* @param defaultValue the default value to return if the iterator is empty
* or if {@code position} is greater than the number of elements
* remaining in {@code iterator}
* @return the element at the specified position in {@code iterator} or
* {@code defaultValue} if {@code iterator} produces fewer than
* {@code position + 1} elements.
* @throws IndexOutOfBoundsException if {@code position} is negative
* @since 4.0
*/
@Nullable
public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) {
checkNonnegative(position);
advance(iterator, position);
return getNext(iterator, defaultValue);
}
/**
* Returns the next element in {@code iterator} or {@code defaultValue} if
* the iterator is empty. The {@link Iterables} analog to this method is
* {@link Iterables#getFirst}.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the next element of {@code iterator} or the default value
* @since 7.0
*/
@Nullable
public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? iterator.next() : defaultValue;
}
/**
* Advances {@code iterator} to the end, returning the last element.
*
* @return the last element of {@code iterator}
* @throws NoSuchElementException if the iterator is empty
*/
public static <T> T getLast(Iterator<T> iterator) {
while (true) {
T current = iterator.next();
if (!iterator.hasNext()) {
return current;
}
}
}
/**
* Advances {@code iterator} to the end, returning the last element or
* {@code defaultValue} if the iterator is empty.
*
* @param defaultValue the default value to return if the iterator is empty
* @return the last element of {@code iterator}
* @since 3.0
*/
@Nullable
public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
return iterator.hasNext() ? getLast(iterator) : defaultValue;
}
/**
* Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times
* or until {@code hasNext()} returns {@code false}, whichever comes first.
*
* @return the number of elements the iterator was advanced
* @since 13.0 (since 3.0 as {@code Iterators.skip})
*/
public static int advance(Iterator<?> iterator, int numberToAdvance) {
checkNotNull(iterator);
checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");
int i;
for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
iterator.next();
}
return i;
}
/**
* Creates an iterator returning the first {@code limitSize} elements of the
* given iterator. If the original iterator does not contain that many
* elements, the returned iterator will have the same behavior as the original
* iterator. The returned iterator supports {@code remove()} if the original
* iterator does.
*
* @param iterator the iterator to limit
* @param limitSize the maximum number of elements in the returned iterator
* @throws IllegalArgumentException if {@code limitSize} is negative
* @since 3.0
*/
public static <T> Iterator<T> limit(
final Iterator<T> iterator, final int limitSize) {
checkNotNull(iterator);
checkArgument(limitSize >= 0, "limit is negative");
return new Iterator<T>() {
private int count;
@Override
public boolean hasNext() {
return count < limitSize && iterator.hasNext();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
count++;
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
};
}
/**
* Returns a view of the supplied {@code iterator} that removes each element
* from the supplied {@code iterator} as it is returned.
*
* <p>The provided iterator must support {@link Iterator#remove()} or
* else the returned iterator will fail on the first call to {@code
* next}.
*
* @param iterator the iterator to remove and return elements from
* @return an iterator that removes and returns elements from the
* supplied iterator
* @since 2.0
*/
public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
checkNotNull(iterator);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
T next = iterator.next();
iterator.remove();
return next;
}
};
}
/**
* Deletes and returns the next value from the iterator, or returns
* {@code defaultValue} if there is no such value.
*/
@Nullable
static <T> T pollNext(Iterator<T> iterator) {
if (iterator.hasNext()) {
T result = iterator.next();
iterator.remove();
return result;
} else {
return null;
}
}
// Methods only in Iterators, not in Iterables
/**
* Clears the iterator using its remove method.
*/
static void clear(Iterator<?> iterator) {
checkNotNull(iterator);
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
}
/**
* Returns an iterator containing the elements of {@code array} in order. The
* returned iterator is a view of the array; subsequent changes to the array
* will be reflected in the iterator.
*
* <p><b>Note:</b> It is often preferable to represent your data using a
* collection type, for example using {@link Arrays#asList(Object[])}, making
* this method unnecessary.
*
* <p>The {@code Iterable} equivalent of this method is either {@link
* Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}},
* or {@link ImmutableList#of}.
*/
public static <T> UnmodifiableIterator<T> forArray(final T... array) {
return forArray(array, 0, array.length, 0);
}
/**
* Returns a list iterator containing the elements in the specified range of
* {@code array} in order, starting at the specified index.
*
* <p>The {@code Iterable} equivalent of this method is {@code
* Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
*/
static <T> UnmodifiableListIterator<T> forArray(
final T[] array, final int offset, int length, int index) {
checkArgument(length >= 0);
int end = offset + length;
// Technically we should give a slightly more descriptive error on overflow
Preconditions.checkPositionIndexes(offset, end, array.length);
Preconditions.checkPositionIndex(index, length);
if (length == 0) {
return emptyListIterator();
}
/*
* We can't use call the two-arg constructor with arguments (offset, end)
* because the returned Iterator is a ListIterator that may be moved back
* past the beginning of the iteration.
*/
return new AbstractIndexedListIterator<T>(length, index) {
@Override protected T get(int index) {
return array[offset + index];
}
};
}
/**
* Returns an iterator containing only {@code value}.
*
* <p>The {@link Iterable} equivalent of this method is {@link
* Collections#singleton}.
*/
public static <T> UnmodifiableIterator<T> singletonIterator(
@Nullable final T value) {
return new UnmodifiableIterator<T>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public T next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return value;
}
};
}
/**
* Adapts an {@code Enumeration} to the {@code Iterator} interface.
*
* <p>This method has no equivalent in {@link Iterables} because viewing an
* {@code Enumeration} as an {@code Iterable} is impossible. However, the
* contents can be <i>copied</i> into a collection using {@link
* Collections#list}.
*/
public static <T> UnmodifiableIterator<T> forEnumeration(
final Enumeration<T> enumeration) {
checkNotNull(enumeration);
return new UnmodifiableIterator<T>() {
@Override
public boolean hasNext() {
return enumeration.hasMoreElements();
}
@Override
public T next() {
return enumeration.nextElement();
}
};
}
/**
* Adapts an {@code Iterator} to the {@code Enumeration} interface.
*
* <p>The {@code Iterable} equivalent of this method is either {@link
* Collections#enumeration} (if you have a {@link Collection}), or
* {@code Iterators.asEnumeration(collection.iterator())}.
*/
public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
checkNotNull(iterator);
return new Enumeration<T>() {
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public T nextElement() {
return iterator.next();
}
};
}
/**
* Implementation of PeekingIterator that avoids peeking unless necessary.
*/
private static class PeekingImpl<E> implements PeekingIterator<E> {
private final Iterator<? extends E> iterator;
private boolean hasPeeked;
private E peekedElement;
public PeekingImpl(Iterator<? extends E> iterator) {
this.iterator = checkNotNull(iterator);
}
@Override
public boolean hasNext() {
return hasPeeked || iterator.hasNext();
}
@Override
public E next() {
if (!hasPeeked) {
return iterator.next();
}
E result = peekedElement;
hasPeeked = false;
peekedElement = null;
return result;
}
@Override
public void remove() {
checkState(!hasPeeked, "Can't remove after you've peeked at next");
iterator.remove();
}
@Override
public E peek() {
if (!hasPeeked) {
peekedElement = iterator.next();
hasPeeked = true;
}
return peekedElement;
}
}
/**
* Returns a {@code PeekingIterator} backed by the given iterator.
*
* <p>Calls to the {@code peek} method with no intervening calls to {@code
* next} do not affect the iteration, and hence return the same object each
* time. A subsequent call to {@code next} is guaranteed to return the same
* object again. For example: <pre> {@code
*
* PeekingIterator<String> peekingIterator =
* Iterators.peekingIterator(Iterators.forArray("a", "b"));
* String a1 = peekingIterator.peek(); // returns "a"
* String a2 = peekingIterator.peek(); // also returns "a"
* String a3 = peekingIterator.next(); // also returns "a"}</pre>
*
* <p>Any structural changes to the underlying iteration (aside from those
* performed by the iterator's own {@link PeekingIterator#remove()} method)
* will leave the iterator in an undefined state.
*
* <p>The returned iterator does not support removal after peeking, as
* explained by {@link PeekingIterator#remove()}.
*
* <p>Note: If the given iterator is already a {@code PeekingIterator},
* it <i>might</i> be returned to the caller, although this is neither
* guaranteed to occur nor required to be consistent. For example, this
* method <i>might</i> choose to pass through recognized implementations of
* {@code PeekingIterator} when the behavior of the implementation is
* known to meet the contract guaranteed by this method.
*
* <p>There is no {@link Iterable} equivalent to this method, so use this
* method to wrap each individual iterator as it is generated.
*
* @param iterator the backing iterator. The {@link PeekingIterator} assumes
* ownership of this iterator, so users should cease making direct calls
* to it after calling this method.
* @return a peeking iterator backed by that iterator. Apart from the
* additional {@link PeekingIterator#peek()} method, this iterator behaves
* exactly the same as {@code iterator}.
*/
public static <T> PeekingIterator<T> peekingIterator(
Iterator<? extends T> iterator) {
if (iterator instanceof PeekingImpl) {
// Safe to cast <? extends T> to <T> because PeekingImpl only uses T
// covariantly (and cannot be subclassed to add non-covariant uses).
@SuppressWarnings("unchecked")
PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
return peeking;
}
return new PeekingImpl<T>(iterator);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <T> PeekingIterator<T> peekingIterator(
PeekingIterator<T> iterator) {
return checkNotNull(iterator);
}
/**
* Returns an iterator over the merged contents of all given
* {@code iterators}, traversing every element of the input iterators.
* Equivalent entries will not be de-duplicated.
*
* <p>Callers must ensure that the source {@code iterators} are in
* non-descending order as this method does not sort its input.
*
* <p>For any equivalent elements across all {@code iterators}, it is
* undefined which element is returned first.
*
* @since 11.0
*/
@Beta
public static <T> UnmodifiableIterator<T> mergeSorted(
Iterable<? extends Iterator<? extends T>> iterators,
Comparator<? super T> comparator) {
checkNotNull(iterators, "iterators");
checkNotNull(comparator, "comparator");
return new MergingIterator<T>(iterators, comparator);
}
/**
* An iterator that performs a lazy N-way merge, calculating the next value
* each time the iterator is polled. This amortizes the sorting cost over the
* iteration and requires less memory than sorting all elements at once.
*
* <p>Retrieving a single element takes approximately O(log(M)) time, where M
* is the number of iterators. (Retrieving all elements takes approximately
* O(N*log(M)) time, where N is the total number of elements.)
*/
private static class MergingIterator<T> extends UnmodifiableIterator<T> {
final Queue<PeekingIterator<T>> queue;
public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators,
final Comparator<? super T> itemComparator) {
// A comparator that's used by the heap, allowing the heap
// to be sorted based on the top of each iterator.
Comparator<PeekingIterator<T>> heapComparator =
new Comparator<PeekingIterator<T>>() {
@Override
public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
return itemComparator.compare(o1.peek(), o2.peek());
}
};
queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator);
for (Iterator<? extends T> iterator : iterators) {
if (iterator.hasNext()) {
queue.add(Iterators.peekingIterator(iterator));
}
}
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
public T next() {
PeekingIterator<T> nextIter = queue.remove();
T next = nextIter.next();
if (nextIter.hasNext()) {
queue.add(nextIter);
}
return next;
}
}
/**
* Precondition tester for {@code Iterator.remove()} that throws an exception with a consistent
* error message.
*/
static void checkRemove(boolean canRemove) {
checkState(canRemove, "no calls to next() since the last call to remove()");
}
/**
* Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
*/
static <T> ListIterator<T> cast(Iterator<T> iterator) {
return (ListIterator<T>) iterator;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
/**
* GWT emulation of {@link ImmutableBiMap}.
*
* @author Hayward Chan
*/
public abstract class ImmutableBiMap<K, V> extends ForwardingImmutableMap<K, V>
implements BiMap<K, V> {
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableBiMap<K, V> of() {
return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE;
}
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
return new SingletonImmutableBiMap<K, V>(
checkNotNull(k1), checkNotNull(v1));
}
public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(k1, v1, k2, v2));
}
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3));
}
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3, k4, v4));
}
public static <K, V> ImmutableBiMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new RegularImmutableBiMap<K, V>(ImmutableMap.of(
k1, v1, k2, v2, k3, v3, k4, v4, k5, v5));
}
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
public Builder() {}
@Override public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
@Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
super.putAll(map);
return this;
}
@Override public ImmutableBiMap<K, V> build() {
ImmutableMap<K, V> map = super.build();
if (map.isEmpty()) {
return of();
}
return new RegularImmutableBiMap<K, V>(super.build());
}
}
public static <K, V> ImmutableBiMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
if (map instanceof ImmutableBiMap) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
return bimap;
}
if (map.isEmpty()) {
return of();
}
ImmutableMap<K, V> immutableMap = ImmutableMap.copyOf(map);
return new RegularImmutableBiMap<K, V>(immutableMap);
}
ImmutableBiMap(Map<K, V> delegate) {
super(delegate);
}
public abstract ImmutableBiMap<V, K> inverse();
@Override public ImmutableSet<V> values() {
return inverse().keySet();
}
public final V forcePut(K key, V value) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import java.io.Serializable;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* GWT emulation of {@link ImmutableMap}. For non sorted maps, it is a thin
* wrapper around {@link java.util.Collections#emptyMap()}, {@link
* Collections#singletonMap(Object, Object)} and {@link java.util.LinkedHashMap}
* for empty, singleton and regular maps respectively. For sorted maps, it's
* a thin wrapper around {@link java.util.TreeMap}.
*
* @see ImmutableSortedMap
*
* @author Hayward Chan
*/
public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable {
ImmutableMap() {}
public static <K, V> ImmutableMap<K, V> of() {
return ImmutableBiMap.of();
}
public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
return ImmutableBiMap.of(k1, v1);
}
public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2));
}
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return new RegularImmutableMap<K, V>(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
}
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new RegularImmutableMap<K, V>(
entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
}
public static <K, V> ImmutableMap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new RegularImmutableMap<K, V>(entryOf(k1, v1),
entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
}
// looking for of() with > 5 entries? Use the builder instead.
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
static <K, V> Entry<K, V> entryOf(K key, V value) {
return Maps.immutableEntry(checkNotNull(key), checkNotNull(value));
}
public static class Builder<K, V> {
final List<Entry<K, V>> entries = Lists.newArrayList();
public Builder() {}
public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
if (entry instanceof ImmutableEntry) {
checkNotNull(entry.getKey());
checkNotNull(entry.getValue());
@SuppressWarnings("unchecked") // all supported methods are covariant
Entry<K, V> immutableEntry = (Entry<K, V>) entry;
entries.add(immutableEntry);
} else {
entries.add(entryOf((K) entry.getKey(), (V) entry.getValue()));
}
return this;
}
public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
public ImmutableMap<K, V> build() {
return fromEntryList(entries);
}
private static <K, V> ImmutableMap<K, V> fromEntryList(
List<Entry<K, V>> entries) {
int size = entries.size();
switch (size) {
case 0:
return of();
case 1:
Entry<K, V> entry = getOnlyElement(entries);
return of(entry.getKey(), entry.getValue());
default:
@SuppressWarnings("unchecked")
Entry<K, V>[] entryArray
= entries.toArray(new Entry[entries.size()]);
return new RegularImmutableMap<K, V>(entryArray);
}
}
}
public static <K, V> ImmutableMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) {
@SuppressWarnings("unchecked") // safe since map is not writable
ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map;
return kvMap;
} else if (map instanceof EnumMap) {
EnumMap<?, ?> enumMap = (EnumMap<?, ?>) map;
for (Map.Entry<?, ?> entry : enumMap.entrySet()) {
checkNotNull(entry.getKey());
checkNotNull(entry.getValue());
}
@SuppressWarnings("unchecked")
// immutable collections are safe for covariant casts
ImmutableMap<K, V> result = ImmutableEnumMap.asImmutable(new EnumMap(enumMap));
return result;
}
int size = map.size();
switch (size) {
case 0:
return of();
case 1:
Entry<? extends K, ? extends V> entry
= getOnlyElement(map.entrySet());
return ImmutableMap.<K, V>of(entry.getKey(), entry.getValue());
default:
Map<K, V> orderPreservingCopy = Maps.newLinkedHashMap();
for (Entry<? extends K, ? extends V> e : map.entrySet()) {
orderPreservingCopy.put(
checkNotNull(e.getKey()), checkNotNull(e.getValue()));
}
return new RegularImmutableMap<K, V>(orderPreservingCopy);
}
}
abstract boolean isPartialView();
public final V put(K k, V v) {
throw new UnsupportedOperationException();
}
public final V remove(Object o) {
throw new UnsupportedOperationException();
}
public final void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
public final void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(@Nullable Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(@Nullable Object value) {
return values().contains(value);
}
private transient ImmutableSet<Entry<K, V>> cachedEntrySet = null;
public final ImmutableSet<Entry<K, V>> entrySet() {
if (cachedEntrySet != null) {
return cachedEntrySet;
}
return cachedEntrySet = createEntrySet();
}
abstract ImmutableSet<Entry<K, V>> createEntrySet();
private transient ImmutableSet<K> cachedKeySet = null;
public ImmutableSet<K> keySet() {
if (cachedKeySet != null) {
return cachedKeySet;
}
return cachedKeySet = createKeySet();
}
ImmutableSet<K> createKeySet() {
return new ImmutableMapKeySet<K, V>(this);
}
private transient ImmutableCollection<V> cachedValues = null;
public ImmutableCollection<V> values() {
if (cachedValues != null) {
return cachedValues;
}
return cachedValues = createValues();
}
// esnickell is editing here
// cached so that this.multimapView().inverse() only computes inverse once
private transient ImmutableSetMultimap<K, V> multimapView;
public ImmutableSetMultimap<K, V> asMultimap() {
ImmutableSetMultimap<K, V> result = multimapView;
return (result == null) ? (multimapView = createMultimapView()) : result;
}
private ImmutableSetMultimap<K, V> createMultimapView() {
ImmutableMap<K, ImmutableSet<V>> map = viewValuesAsImmutableSet();
return new ImmutableSetMultimap<K, V>(map, map.size(), null);
}
private ImmutableMap<K, ImmutableSet<V>> viewValuesAsImmutableSet() {
final Map<K, V> outer = this;
return new ImmutableMap<K, ImmutableSet<V>>() {
@Override
public int size() {
return outer.size();
}
@Override
public ImmutableSet<V> get(@Nullable Object key) {
V outerValue = outer.get(key);
return outerValue == null ? null : ImmutableSet.of(outerValue);
}
@Override
ImmutableSet<Entry<K, ImmutableSet<V>>> createEntrySet() {
return new ImmutableSet<Entry<K, ImmutableSet<V>>>() {
@Override
public UnmodifiableIterator<Entry<K, ImmutableSet<V>>> iterator() {
final Iterator<Entry<K,V>> outerEntryIterator = outer.entrySet().iterator();
return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() {
@Override
public boolean hasNext() {
return outerEntryIterator.hasNext();
}
@Override
public Entry<K, ImmutableSet<V>> next() {
final Entry<K, V> outerEntry = outerEntryIterator.next();
return new AbstractMapEntry<K, ImmutableSet<V>>() {
@Override
public K getKey() {
return outerEntry.getKey();
}
@Override
public ImmutableSet<V> getValue() {
return ImmutableSet.of(outerEntry.getValue());
}
};
}
};
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int size() {
return outer.size();
}
};
}
@Override
boolean isPartialView() {
return false;
}
};
}
ImmutableCollection<V> createValues() {
return new ImmutableMapValues<K, V>(this);
}
@Override public boolean equals(@Nullable Object object) {
return Maps.equalsImpl(this, object);
}
@Override public int hashCode() {
// not caching hash code since it could change if map values are mutable
// in a way that modifies their hash codes
return entrySet().hashCode();
}
@Override public String toString() {
return Maps.toStringImpl(this);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Fixed-size {@link Table} implementation backed by a two-dimensional array.
*
* <p>The allowed row and column keys must be supplied when the table is
* created. The table always contains a mapping for every row key / column pair.
* The value corresponding to a given row and column is null unless another
* value is provided.
*
* <p>The table's size is constant: the product of the number of supplied row
* keys and the number of supplied column keys. The {@code remove} and {@code
* clear} methods are not supported by the table or its views. The {@link
* #erase} and {@link #eraseAll} methods may be used instead.
*
* <p>The ordering of the row and column keys provided when the table is
* constructed determines the iteration ordering across rows and columns in the
* table's views. None of the view iterators support {@link Iterator#remove}.
* If the table is modified after an iterator is created, the iterator remains
* valid.
*
* <p>This class requires less memory than the {@link HashBasedTable} and {@link
* TreeBasedTable} implementations, except when the table is sparse.
*
* <p>Null row keys or column keys are not permitted.
*
* <p>This class provides methods involving the underlying array structure,
* where the array indices correspond to the position of a row or column in the
* lists of allowed keys and values. See the {@link #at}, {@link #set}, {@link
* #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} methods for more
* details.
*
* <p>Note that this implementation is not synchronized. If multiple threads
* access the same cell of an {@code ArrayTable} concurrently and one of the
* threads modifies its value, there is no guarantee that the new value will be
* fully visible to the other threads. To guarantee that modifications are
* visible, synchronize access to the table. Unlike other {@code Table}
* implementations, synchronization is unnecessary between a thread that writes
* to one cell and a thread that reads from another.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
* {@code Table}</a>.
*
* @author Jared Levy
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class ArrayTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable {
/**
* Creates an empty {@code ArrayTable}.
*
* @param rowKeys row keys that may be stored in the generated table
* @param columnKeys column keys that may be stored in the generated table
* @throws NullPointerException if any of the provided keys is null
* @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys}
* contains duplicates or is empty
*/
public static <R, C, V> ArrayTable<R, C, V> create(
Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
return new ArrayTable<R, C, V>(rowKeys, columnKeys);
}
/*
* TODO(jlevy): Add factory methods taking an Enum class, instead of an
* iterable, to specify the allowed row keys and/or column keys. Note that
* custom serialization logic is needed to support different enum sizes during
* serialization and deserialization.
*/
/**
* Creates an {@code ArrayTable} with the mappings in the provided table.
*
* <p>If {@code table} includes a mapping with row key {@code r} and a
* separate mapping with column key {@code c}, the returned table contains a
* mapping with row key {@code r} and column key {@code c}. If that row key /
* column key pair in not in {@code table}, the pair maps to {@code null} in
* the generated table.
*
* <p>The returned table allows subsequent {@code put} calls with the row keys
* in {@code table.rowKeySet()} and the column keys in {@code
* table.columnKeySet()}. Calling {@link #put} with other keys leads to an
* {@code IllegalArgumentException}.
*
* <p>The ordering of {@code table.rowKeySet()} and {@code
* table.columnKeySet()} determines the row and column iteration ordering of
* the returned table.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if the provided table is empty
*/
public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) {
return (table instanceof ArrayTable<?, ?, ?>)
? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table)
: new ArrayTable<R, C, V>(table);
}
private final ImmutableList<R> rowList;
private final ImmutableList<C> columnList;
// TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
private final ImmutableMap<R, Integer> rowKeyToIndex;
private final ImmutableMap<C, Integer> columnKeyToIndex;
private final V[][] array;
private ArrayTable(Iterable<? extends R> rowKeys,
Iterable<? extends C> columnKeys) {
this.rowList = ImmutableList.copyOf(rowKeys);
this.columnList = ImmutableList.copyOf(columnKeys);
checkArgument(!rowList.isEmpty());
checkArgument(!columnList.isEmpty());
/*
* TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when
* columnKeys is empty but rowKeys isn't, the table is empty but
* containsRow() can return true and rowKeySet() isn't empty.
*/
rowKeyToIndex = index(rowList);
columnKeyToIndex = index(columnList);
@SuppressWarnings("unchecked")
V[][] tmpArray
= (V[][]) new Object[rowList.size()][columnList.size()];
array = tmpArray;
// Necessary because in GWT the arrays are initialized with "undefined" instead of null.
eraseAll();
}
private static <E> ImmutableMap<E, Integer> index(List<E> list) {
ImmutableMap.Builder<E, Integer> columnBuilder = ImmutableMap.builder();
for (int i = 0; i < list.size(); i++) {
columnBuilder.put(list.get(i), i);
}
return columnBuilder.build();
}
private ArrayTable(Table<R, C, V> table) {
this(table.rowKeySet(), table.columnKeySet());
putAll(table);
}
private ArrayTable(ArrayTable<R, C, V> table) {
rowList = table.rowList;
columnList = table.columnList;
rowKeyToIndex = table.rowKeyToIndex;
columnKeyToIndex = table.columnKeyToIndex;
@SuppressWarnings("unchecked")
V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()];
array = copy;
// Necessary because in GWT the arrays are initialized with "undefined" instead of null.
eraseAll();
for (int i = 0; i < rowList.size(); i++) {
System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
}
}
private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> {
private final ImmutableMap<K, Integer> keyIndex;
private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
this.keyIndex = keyIndex;
}
@Override
public Set<K> keySet() {
return keyIndex.keySet();
}
K getKey(int index) {
return keyIndex.keySet().asList().get(index);
}
abstract String getKeyRole();
@Nullable abstract V getValue(int index);
@Nullable abstract V setValue(int index, V newValue);
@Override
public int size() {
return keyIndex.size();
}
@Override
public boolean isEmpty() {
return keyIndex.isEmpty();
}
@Override
protected Set<Entry<K, V>> createEntrySet() {
return new Maps.EntrySet<K, V>() {
@Override
Map<K, V> map() {
return ArrayMap.this;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
@Override
protected Entry<K, V> get(final int index) {
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return ArrayMap.this.getKey(index);
}
@Override
public V getValue() {
return ArrayMap.this.getValue(index);
}
@Override
public V setValue(V value) {
return ArrayMap.this.setValue(index, value);
}
};
}
};
}
};
}
// TODO(user): consider an optimized values() implementation
@Override
public boolean containsKey(@Nullable Object key) {
return keyIndex.containsKey(key);
}
@Override
public V get(@Nullable Object key) {
Integer index = keyIndex.get(key);
if (index == null) {
return null;
} else {
return getValue(index);
}
}
@Override
public V put(K key, V value) {
Integer index = keyIndex.get(key);
if (index == null) {
throw new IllegalArgumentException(
getKeyRole() + " " + key + " not in " + keyIndex.keySet());
}
return setValue(index, value);
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
/**
* Returns, as an immutable list, the row keys provided when the table was
* constructed, including those that are mapped to null values only.
*/
public ImmutableList<R> rowKeyList() {
return rowList;
}
/**
* Returns, as an immutable list, the column keys provided when the table was
* constructed, including those that are mapped to null values only.
*/
public ImmutableList<C> columnKeyList() {
return columnList;
}
/**
* Returns the value corresponding to the specified row and column indices.
* The same value is returned by {@code
* get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but
* this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @return the value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code
* rowIndex} is greater then or equal to the number of allowed row keys,
* or {@code columnIndex} is greater then or equal to the number of
* allowed column keys
*/
public V at(int rowIndex, int columnIndex) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
return array[rowIndex][columnIndex];
}
/**
* Associates {@code value} with the specified row and column indices. The
* logic {@code
* put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)}
* has the same behavior, but this method runs more quickly.
*
* @param rowIndex position of the row key in {@link #rowKeyList()}
* @param columnIndex position of the row key in {@link #columnKeyList()}
* @param value value to store in the table
* @return the previous value with the specified row and column
* @throws IndexOutOfBoundsException if either index is negative, {@code
* rowIndex} is greater then or equal to the number of allowed row keys,
* or {@code columnIndex} is greater then or equal to the number of
* allowed column keys
*/
public V set(int rowIndex, int columnIndex, @Nullable V value) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
V oldValue = array[rowIndex][columnIndex];
array[rowIndex][columnIndex] = value;
return oldValue;
}
/**
* Not supported. Use {@link #eraseAll} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #eraseAll}
*/
@Override
@Deprecated public void clear() {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with every pair of allowed row and column
* keys.
*/
public void eraseAll() {
for (V[] row : array) {
Arrays.fill(row, null);
}
}
/**
* Returns {@code true} if the provided keys are among the keys provided when
* the table was constructed.
*/
@Override
public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
return containsRow(rowKey) && containsColumn(columnKey);
}
/**
* Returns {@code true} if the provided column key is among the column keys
* provided when the table was constructed.
*/
@Override
public boolean containsColumn(@Nullable Object columnKey) {
return columnKeyToIndex.containsKey(columnKey);
}
/**
* Returns {@code true} if the provided row key is among the row keys
* provided when the table was constructed.
*/
@Override
public boolean containsRow(@Nullable Object rowKey) {
return rowKeyToIndex.containsKey(rowKey);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (V[] row : array) {
for (V element : row) {
if (Objects.equal(value, element)) {
return true;
}
}
}
return false;
}
@Override
public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (rowIndex == null || columnIndex == null)
? null : at(rowIndex, columnIndex);
}
/**
* Always returns {@code false}.
*/
@Override
public boolean isEmpty() {
return false;
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if {@code rowKey} is not in {@link
* #rowKeySet()} or {@code columnKey} is not in {@link #columnKeySet()}.
*/
@Override
public V put(R rowKey, C columnKey, @Nullable V value) {
checkNotNull(rowKey);
checkNotNull(columnKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
Integer columnIndex = columnKeyToIndex.get(columnKey);
checkArgument(columnIndex != null,
"Column %s not in %s", columnKey, columnList);
return set(rowIndex, columnIndex, value);
}
/*
* TODO(jlevy): Consider creating a merge() method, similar to putAll() but
* copying non-null values only.
*/
/**
* {@inheritDoc}
*
* <p>If {@code table} is an {@code ArrayTable}, its null values will be
* stored in this table, possibly replacing values that were previously
* non-null.
*
* @throws NullPointerException if {@code table} has a null key
* @throws IllegalArgumentException if any of the provided table's row keys or
* column keys is not in {@link #rowKeySet()} or {@link #columnKeySet()}
*/
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
super.putAll(table);
}
/**
* Not supported. Use {@link #erase} instead.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #erase}
*/
@Override
@Deprecated public V remove(Object rowKey, Object columnKey) {
throw new UnsupportedOperationException();
}
/**
* Associates the value {@code null} with the specified keys, assuming both
* keys are valid. If either key is null or isn't among the keys provided
* during construction, this method has no effect.
*
* <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when
* both provided keys are valid.
*
* @param rowKey row key of mapping to be erased
* @param columnKey column key of mapping to be erased
* @return the value previously associated with the keys, or {@code null} if
* no mapping existed for the keys
*/
public V erase(@Nullable Object rowKey, @Nullable Object columnKey) {
Integer rowIndex = rowKeyToIndex.get(rowKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
if (rowIndex == null || columnIndex == null) {
return null;
}
return set(rowIndex, columnIndex, null);
}
// TODO(jlevy): Add eraseRow and eraseColumn methods?
@Override
public int size() {
return rowList.size() * columnList.size();
}
/**
* Returns an unmodifiable set of all row key / column key / value
* triplets. Changes to the table will update the returned set.
*
* <p>The returned set's iterator traverses the mappings with the first row
* key, the mappings with the second row key, and so on.
*
* <p>The value in the returned cells may change if the table subsequently
* changes.
*
* @return set of table cells consisting of row key / column key / value
* triplets
*/
@Override
public Set<Cell<R, C, V>> cellSet() {
return super.cellSet();
}
@Override
Iterator<Cell<R, C, V>> cellIterator() {
return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) {
@Override protected Cell<R, C, V> get(final int index) {
return new Tables.AbstractCell<R, C, V>() {
final int rowIndex = index / columnList.size();
final int columnIndex = index % columnList.size();
@Override
public R getRowKey() {
return rowList.get(rowIndex);
}
@Override
public C getColumnKey() {
return columnList.get(columnIndex);
}
@Override
public V getValue() {
return at(rowIndex, columnIndex);
}
};
}
};
}
/**
* Returns a view of all mappings that have the given column key. If the
* column key isn't in {@link #columnKeySet()}, an empty immutable map is
* returned.
*
* <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map
* associates the row key with the corresponding value in the table. Changes
* to the returned map will update the underlying table, and vice versa.
*
* @param columnKey key of column to search for in the table
* @return the corresponding map from row keys to values
*/
@Override
public Map<R, V> column(C columnKey) {
checkNotNull(columnKey);
Integer columnIndex = columnKeyToIndex.get(columnKey);
return (columnIndex == null)
? ImmutableMap.<R, V>of() : new Column(columnIndex);
}
private class Column extends ArrayMap<R, V> {
final int columnIndex;
Column(int columnIndex) {
super(rowKeyToIndex);
this.columnIndex = columnIndex;
}
@Override
String getKeyRole() {
return "Row";
}
@Override
V getValue(int index) {
return at(index, columnIndex);
}
@Override
V setValue(int index, V newValue) {
return set(index, columnIndex, newValue);
}
}
/**
* Returns an immutable set of the valid column keys, including those that
* are associated with null values only.
*
* @return immutable set of column keys
*/
@Override
public ImmutableSet<C> columnKeySet() {
return columnKeyToIndex.keySet();
}
private transient ColumnMap columnMap;
@Override
public Map<C, Map<R, V>> columnMap() {
ColumnMap map = columnMap;
return (map == null) ? columnMap = new ColumnMap() : map;
}
private class ColumnMap extends ArrayMap<C, Map<R, V>> {
private ColumnMap() {
super(columnKeyToIndex);
}
@Override
String getKeyRole() {
return "Column";
}
@Override
Map<R, V> getValue(int index) {
return new Column(index);
}
@Override
Map<R, V> setValue(int index, Map<R, V> newValue) {
throw new UnsupportedOperationException();
}
@Override
public Map<R, V> put(C key, Map<R, V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a view of all mappings that have the given row key. If the
* row key isn't in {@link #rowKeySet()}, an empty immutable map is
* returned.
*
* <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned
* map associates the column key with the corresponding value in the
* table. Changes to the returned map will update the underlying table, and
* vice versa.
*
* @param rowKey key of row to search for in the table
* @return the corresponding map from column keys to values
*/
@Override
public Map<C, V> row(R rowKey) {
checkNotNull(rowKey);
Integer rowIndex = rowKeyToIndex.get(rowKey);
return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex);
}
private class Row extends ArrayMap<C, V> {
final int rowIndex;
Row(int rowIndex) {
super(columnKeyToIndex);
this.rowIndex = rowIndex;
}
@Override
String getKeyRole() {
return "Column";
}
@Override
V getValue(int index) {
return at(rowIndex, index);
}
@Override
V setValue(int index, V newValue) {
return set(rowIndex, index, newValue);
}
}
/**
* Returns an immutable set of the valid row keys, including those that are
* associated with null values only.
*
* @return immutable set of row keys
*/
@Override
public ImmutableSet<R> rowKeySet() {
return rowKeyToIndex.keySet();
}
private transient RowMap rowMap;
@Override
public Map<R, Map<C, V>> rowMap() {
RowMap map = rowMap;
return (map == null) ? rowMap = new RowMap() : map;
}
private class RowMap extends ArrayMap<R, Map<C, V>> {
private RowMap() {
super(rowKeyToIndex);
}
@Override
String getKeyRole() {
return "Row";
}
@Override
Map<C, V> getValue(int index) {
return new Row(index);
}
@Override
Map<C, V> setValue(int index, Map<C, V> newValue) {
throw new UnsupportedOperationException();
}
@Override
public Map<C, V> put(R key, Map<C, V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns an unmodifiable collection of all values, which may contain
* duplicates. Changes to the table will update the returned collection.
*
* <p>The returned collection's iterator traverses the values of the first row
* key, the values of the second row key, and so on.
*
* @return collection of values
*/
@Override
public Collection<V> values() {
return super.values();
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.base.Function;
import com.google.gwt.user.client.Timer;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* MapMaker emulation. Since Javascript is single-threaded and have no references, this reduces to
* the creation of expiring and computing maps.
*
* @author Charles Fry
*/
public final class MapMaker extends GenericMapMaker<Object, Object> {
// TODO(fry,user): ConcurrentHashMap never throws a CME when mutating the map during iteration, but
// this implementation (based on a LHM) does. This will all be replaced soon anyways, so leaving
// it as is for now.
private static class ExpiringComputingMap<K, V> extends LinkedHashMap<K, V>
implements ConcurrentMap<K, V> {
private final long expirationMillis;
private final Function<? super K, ? extends V> computer;
private final int maximumSize;
ExpiringComputingMap(
long expirationMillis, int maximumSize, int initialCapacity) {
this(expirationMillis, null, maximumSize, initialCapacity);
}
ExpiringComputingMap(long expirationMillis, Function<? super K, ? extends V> computer,
int maximumSize, int initialCapacity) {
super(initialCapacity, /* ignored loadFactor */ 0.75f, (maximumSize != -1));
this.expirationMillis = expirationMillis;
this.computer = computer;
this.maximumSize = maximumSize;
}
@Override
public V put(K key, V value) {
V result = super.put(key, value);
if (expirationMillis > 0) {
scheduleRemoval(key, value);
}
return result;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> ignored) {
return (maximumSize == -1) ? false : size() > maximumSize;
}
@Override
public V putIfAbsent(K key, V value) {
if (!containsKey(key)) {
return put(key, value);
} else {
return get(key);
}
}
@Override
public boolean remove(Object key, Object value) {
if (containsKey(key) && get(key).equals(value)) {
remove(key);
return true;
}
return false;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
if (containsKey(key) && get(key).equals(oldValue)) {
put(key, newValue);
return true;
}
return false;
}
@Override
public V replace(K key, V value) {
return containsKey(key) ? put(key, value) : null;
}
private void scheduleRemoval(final K key, final V value) {
// from MapMaker
/*
* TODO: Keep weak reference to map, too. Build a priority queue out of the entries themselves
* instead of creating a task per entry. Then, we could have one recurring task per map (which
* would clean the entire map and then reschedule itself depending upon when the next
* expiration comes). We also want to avoid removing an entry prematurely if the entry was set
* to the same value again.
*/
Timer timer = new Timer() {
@Override
public void run() {
remove(key, value);
}
};
timer.schedule((int) expirationMillis);
}
@Override
public V get(Object k) {
// from CustomConcurrentHashMap
V result = super.get(k);
if (result == null && computer != null) {
/*
* This cast isn't safe, but we can rely on the fact that K is almost always passed to
* Map.get(), and tools like IDEs and Findbugs can catch situations where this isn't the
* case.
*
* The alternative is to add an overloaded method, but the chances of a user calling get()
* instead of the new API and the risks inherent in adding a new API outweigh this little
* hole.
*/
@SuppressWarnings("unchecked")
K key = (K) k;
result = compute(key);
}
return result;
}
private V compute(K key) {
// from MapMaker
V value;
try {
value = computer.apply(key);
} catch (Throwable t) {
throw new ComputationException(t);
}
if (value == null) {
String message = computer + " returned null for key " + key + ".";
throw new NullPointerException(message);
}
put(key, value);
return value;
}
}
private int initialCapacity = 16;
private long expirationMillis = 0;
private int maximumSize = -1;
private boolean useCustomMap;
public MapMaker() {}
@Override
public MapMaker initialCapacity(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException();
}
this.initialCapacity = initialCapacity;
return this;
}
@Override
MapMaker expireAfterWrite(long duration, TimeUnit unit) {
if (expirationMillis != 0) {
throw new IllegalStateException(
"expiration time of " + expirationMillis + " ns was already set");
}
if (duration <= 0) {
throw new IllegalArgumentException("invalid duration: " + duration);
}
this.expirationMillis = unit.toMillis(duration);
useCustomMap = true;
return this;
}
@Override
MapMaker maximumSize(int maximumSize) {
if (this.maximumSize != -1) {
throw new IllegalStateException("maximum size of " + maximumSize + " was already set");
}
if (maximumSize < 0) {
throw new IllegalArgumentException("invalid maximum size: " + maximumSize);
}
this.maximumSize = maximumSize;
useCustomMap = true;
return this;
}
@Override
public MapMaker concurrencyLevel(int concurrencyLevel) {
if (concurrencyLevel < 1) {
throw new IllegalArgumentException("GWT only supports a concurrency level of 1");
}
// GWT technically only supports concurrencyLevel == 1, but we silently
// ignore other positive values.
return this;
}
@Override
public <K, V> ConcurrentMap<K, V> makeMap() {
return useCustomMap
? new ExpiringComputingMap<K, V>(expirationMillis, null, maximumSize, initialCapacity)
: new ConcurrentHashMap<K, V>(initialCapacity);
}
@Override
public <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computer) {
return new ExpiringComputingMap<K, V>(
expirationMillis, computer, maximumSize, initialCapacity);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Comparator;
import java.util.SortedMap;
/**
* GWT emulated version of {@link RegularImmutableSortedMap}.
*
* @author Chris Povirk
*/
final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> {
RegularImmutableSortedMap(SortedMap<K, V> delegate, Comparator<? super K> comparator) {
super(delegate, comparator);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map.Entry;
import javax.annotation.Nullable;
/**
* An immutable {@link ListMultimap} with reliable user-specified key and value
* iteration order. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableListMultimap(ListMultimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableListMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableListMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableListMultimap<K, V>
extends ImmutableMultimap<K, V>
implements ListMultimap<K, V> {
/** Returns the empty multimap. */
// Casting is safe because the multimap will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableListMultimap<K, V> of() {
return (ImmutableListMultimap<K, V>) EmptyImmutableListMultimap.INSTANCE;
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(K k1, V v1, K k2, V v2) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
return builder.build();
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableListMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
builder.put(k1, v1);
builder.put(k2, v2);
builder.put(k3, v3);
builder.put(k4, v4);
builder.put(k5, v5);
return builder.build();
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* A builder for creating immutable {@code ListMultimap} instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableListMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static final class Builder<K, V>
extends ImmutableMultimap.Builder<K, V> {
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableListMultimap#builder}.
*/
public Builder() {}
@Override public Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
/**
* {@inheritDoc}
*
* @since 11.0
*/
@Override public Builder<K, V> put(
Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
@Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(K key, V... values) {
super.putAll(key, values);
return this;
}
@Override public Builder<K, V> putAll(
Multimap<? extends K, ? extends V> multimap) {
super.putAll(multimap);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Override
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
/**
* {@inheritDoc}
*
* @since 8.0
*/
@Override
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
/**
* Returns a newly-created immutable list multimap.
*/
@Override public ImmutableListMultimap<K, V> build() {
return (ImmutableListMultimap<K, V>) super.build();
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code
* multimap}. The generated multimap's key and value orderings correspond to
* the iteration ordering of the {@code multimap.asMap()} view.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableListMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap.isEmpty()) {
return of();
}
// TODO(user): copy ImmutableSetMultimap by using asList() on the sets
if (multimap instanceof ImmutableListMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableListMultimap<K, V> kvMultimap
= (ImmutableListMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder();
int size = 0;
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
ImmutableList<V> list = ImmutableList.copyOf(entry.getValue());
if (!list.isEmpty()) {
builder.put(entry.getKey(), list);
size += list.size();
}
}
return new ImmutableListMultimap<K, V>(builder.build(), size);
}
ImmutableListMultimap(ImmutableMap<K, ImmutableList<V>> map, int size) {
super(map, size);
}
// views
/**
* Returns an immutable list of the values for the given key. If no mappings
* in the multimap have the provided key, an empty immutable list is
* returned. The values are in the same order as the parameters used to build
* this multimap.
*/
@Override public ImmutableList<V> get(@Nullable K key) {
// This cast is safe as its type is known in constructor.
ImmutableList<V> list = (ImmutableList<V>) map.get(key);
return (list == null) ? ImmutableList.<V>of() : list;
}
private transient ImmutableListMultimap<V, K> inverse;
/**
* {@inheritDoc}
*
* <p>Because an inverse of a list multimap can contain multiple pairs with
* the same key and value, this method returns an {@code
* ImmutableListMultimap} rather than the {@code ImmutableMultimap} specified
* in the {@code ImmutableMultimap} class.
*
* @since 11.0
*/
@Override
public ImmutableListMultimap<V, K> inverse() {
ImmutableListMultimap<V, K> result = inverse;
return (result == null) ? (inverse = invert()) : result;
}
private ImmutableListMultimap<V, K> invert() {
Builder<V, K> builder = builder();
for (Entry<K, V> entry : entries()) {
builder.put(entry.getValue(), entry.getKey());
}
ImmutableListMultimap<V, K> invertedMultimap = builder.build();
invertedMultimap.inverse = this;
return invertedMultimap;
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableList<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated @Override public ImmutableList<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Synchronized collection views. The returned synchronized collection views are
* serializable if the backing collection and the mutex are serializable.
*
* <p>If {@code null} is passed as the {@code mutex} parameter to any of this
* class's top-level methods or inner class constructors, the created object
* uses itself as the synchronization mutex.
*
* <p>This class should be used by other collection classes only.
*
* @author Mike Bostock
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
final class Synchronized {
private Synchronized() {}
static class SynchronizedObject implements Serializable {
final Object delegate;
final Object mutex;
SynchronizedObject(Object delegate, @Nullable Object mutex) {
this.delegate = checkNotNull(delegate);
this.mutex = (mutex == null) ? this : mutex;
}
Object delegate() {
return delegate;
}
// No equals and hashCode; see ForwardingObject for details.
@Override public String toString() {
synchronized (mutex) {
return delegate.toString();
}
}
// Serialization invokes writeObject only when it's private.
// The SynchronizedObject subclasses don't need a writeObject method since
// they don't contain any non-transient member variables, while the
// following writeObject() handles the SynchronizedObject members.
}
private static <E> Collection<E> collection(
Collection<E> collection, @Nullable Object mutex) {
return new SynchronizedCollection<E>(collection, mutex);
}
@VisibleForTesting static class SynchronizedCollection<E>
extends SynchronizedObject implements Collection<E> {
private SynchronizedCollection(
Collection<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Collection<E> delegate() {
return (Collection<E>) super.delegate();
}
@Override
public boolean add(E e) {
synchronized (mutex) {
return delegate().add(e);
}
}
@Override
public boolean addAll(Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(c);
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean contains(Object o) {
synchronized (mutex) {
return delegate().contains(o);
}
}
@Override
public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return delegate().containsAll(c);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Iterator<E> iterator() {
return delegate().iterator(); // manually synchronized
}
@Override
public boolean remove(Object o) {
synchronized (mutex) {
return delegate().remove(o);
}
}
@Override
public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return delegate().removeAll(c);
}
}
@Override
public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return delegate().retainAll(c);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Object[] toArray() {
synchronized (mutex) {
return delegate().toArray();
}
}
@Override
public <T> T[] toArray(T[] a) {
synchronized (mutex) {
return delegate().toArray(a);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting static <E> Set<E> set(Set<E> set, @Nullable Object mutex) {
return new SynchronizedSet<E>(set, mutex);
}
static class SynchronizedSet<E>
extends SynchronizedCollection<E> implements Set<E> {
SynchronizedSet(Set<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Set<E> delegate() {
return (Set<E>) super.delegate();
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static <E> SortedSet<E> sortedSet(
SortedSet<E> set, @Nullable Object mutex) {
return new SynchronizedSortedSet<E>(set, mutex);
}
static class SynchronizedSortedSet<E> extends SynchronizedSet<E>
implements SortedSet<E> {
SynchronizedSortedSet(SortedSet<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSet<E> delegate() {
return (SortedSet<E>) super.delegate();
}
@Override
public Comparator<? super E> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
synchronized (mutex) {
return sortedSet(delegate().subSet(fromElement, toElement), mutex);
}
}
@Override
public SortedSet<E> headSet(E toElement) {
synchronized (mutex) {
return sortedSet(delegate().headSet(toElement), mutex);
}
}
@Override
public SortedSet<E> tailSet(E fromElement) {
synchronized (mutex) {
return sortedSet(delegate().tailSet(fromElement), mutex);
}
}
@Override
public E first() {
synchronized (mutex) {
return delegate().first();
}
}
@Override
public E last() {
synchronized (mutex) {
return delegate().last();
}
}
private static final long serialVersionUID = 0;
}
private static <E> List<E> list(List<E> list, @Nullable Object mutex) {
return (list instanceof RandomAccess)
? new SynchronizedRandomAccessList<E>(list, mutex)
: new SynchronizedList<E>(list, mutex);
}
private static class SynchronizedList<E> extends SynchronizedCollection<E>
implements List<E> {
SynchronizedList(List<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override List<E> delegate() {
return (List<E>) super.delegate();
}
@Override
public void add(int index, E element) {
synchronized (mutex) {
delegate().add(index, element);
}
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
synchronized (mutex) {
return delegate().addAll(index, c);
}
}
@Override
public E get(int index) {
synchronized (mutex) {
return delegate().get(index);
}
}
@Override
public int indexOf(Object o) {
synchronized (mutex) {
return delegate().indexOf(o);
}
}
@Override
public int lastIndexOf(Object o) {
synchronized (mutex) {
return delegate().lastIndexOf(o);
}
}
@Override
public ListIterator<E> listIterator() {
return delegate().listIterator(); // manually synchronized
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate().listIterator(index); // manually synchronized
}
@Override
public E remove(int index) {
synchronized (mutex) {
return delegate().remove(index);
}
}
@Override
public E set(int index, E element) {
synchronized (mutex) {
return delegate().set(index, element);
}
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
synchronized (mutex) {
return list(delegate().subList(fromIndex, toIndex), mutex);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedRandomAccessList<E>
extends SynchronizedList<E> implements RandomAccess {
SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) {
super(list, mutex);
}
private static final long serialVersionUID = 0;
}
static <E> Multiset<E> multiset(
Multiset<E> multiset, @Nullable Object mutex) {
if (multiset instanceof SynchronizedMultiset ||
multiset instanceof ImmutableMultiset) {
return multiset;
}
return new SynchronizedMultiset<E>(multiset, mutex);
}
private static class SynchronizedMultiset<E> extends SynchronizedCollection<E>
implements Multiset<E> {
transient Set<E> elementSet;
transient Set<Entry<E>> entrySet;
SynchronizedMultiset(Multiset<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Multiset<E> delegate() {
return (Multiset<E>) super.delegate();
}
@Override
public int count(Object o) {
synchronized (mutex) {
return delegate().count(o);
}
}
@Override
public int add(E e, int n) {
synchronized (mutex) {
return delegate().add(e, n);
}
}
@Override
public int remove(Object o, int n) {
synchronized (mutex) {
return delegate().remove(o, n);
}
}
@Override
public int setCount(E element, int count) {
synchronized (mutex) {
return delegate().setCount(element, count);
}
}
@Override
public boolean setCount(E element, int oldCount, int newCount) {
synchronized (mutex) {
return delegate().setCount(element, oldCount, newCount);
}
}
@Override
public Set<E> elementSet() {
synchronized (mutex) {
if (elementSet == null) {
elementSet = typePreservingSet(delegate().elementSet(), mutex);
}
return elementSet;
}
}
@Override
public Set<Entry<E>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = typePreservingSet(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> Multimap<K, V> multimap(
Multimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedMultimap ||
multimap instanceof ImmutableMultimap) {
return multimap;
}
return new SynchronizedMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedMultimap<K, V> extends SynchronizedObject
implements Multimap<K, V> {
transient Set<K> keySet;
transient Collection<V> valuesCollection;
transient Collection<Map.Entry<K, V>> entries;
transient Map<K, Collection<V>> asMap;
transient Multiset<K> keys;
@SuppressWarnings("unchecked")
@Override Multimap<K, V> delegate() {
return (Multimap<K, V>) super.delegate();
}
SynchronizedMultimap(Multimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public boolean containsEntry(Object key, Object value) {
synchronized (mutex) {
return delegate().containsEntry(key, value);
}
}
@Override
public Collection<V> get(K key) {
synchronized (mutex) {
return typePreservingCollection(delegate().get(key), mutex);
}
}
@Override
public boolean put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().putAll(key, values);
}
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
synchronized (mutex) {
return delegate().putAll(multimap);
}
}
@Override
public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public boolean remove(Object key, Object value) {
synchronized (mutex) {
return delegate().remove(key, value);
}
}
@Override
public Collection<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = typePreservingSet(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (valuesCollection == null) {
valuesCollection = collection(delegate().values(), mutex);
}
return valuesCollection;
}
}
@Override
public Collection<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entries == null) {
entries = typePreservingCollection(delegate().entries(), mutex);
}
return entries;
}
}
@Override
public Map<K, Collection<V>> asMap() {
synchronized (mutex) {
if (asMap == null) {
asMap = new SynchronizedAsMap<K, V>(delegate().asMap(), mutex);
}
return asMap;
}
}
@Override
public Multiset<K> keys() {
synchronized (mutex) {
if (keys == null) {
keys = multiset(delegate().keys(), mutex);
}
return keys;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> ListMultimap<K, V> listMultimap(
ListMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedListMultimap ||
multimap instanceof ImmutableListMultimap) {
return multimap;
}
return new SynchronizedListMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedListMultimap<K, V>
extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> {
SynchronizedListMultimap(
ListMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
synchronized (mutex) {
return list(delegate().get(key), mutex);
}
}
@Override public List<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SetMultimap<K, V> setMultimap(
SetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSetMultimap ||
multimap instanceof ImmutableSetMultimap) {
return multimap;
}
return new SynchronizedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSetMultimap<K, V>
extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> {
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedSetMultimap(
SetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
synchronized (mutex) {
return set(delegate().get(key), mutex);
}
}
@Override public Set<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override public Set<Map.Entry<K, V>> entries() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entries(), mutex);
}
return entrySet;
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedSetMultimap<K, V> sortedSetMultimap(
SortedSetMultimap<K, V> multimap, @Nullable Object mutex) {
if (multimap instanceof SynchronizedSortedSetMultimap) {
return multimap;
}
return new SynchronizedSortedSetMultimap<K, V>(multimap, mutex);
}
private static class SynchronizedSortedSetMultimap<K, V>
extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> {
SynchronizedSortedSetMultimap(
SortedSetMultimap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
synchronized (mutex) {
return sortedSet(delegate().get(key), mutex);
}
}
@Override public SortedSet<V> removeAll(Object key) {
synchronized (mutex) {
return delegate().removeAll(key); // copy not synchronized
}
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
synchronized (mutex) {
return delegate().replaceValues(key, values); // copy not synchronized
}
}
@Override
public Comparator<? super V> valueComparator() {
synchronized (mutex) {
return delegate().valueComparator();
}
}
private static final long serialVersionUID = 0;
}
private static <E> Collection<E> typePreservingCollection(
Collection<E> collection, @Nullable Object mutex) {
if (collection instanceof SortedSet) {
return sortedSet((SortedSet<E>) collection, mutex);
}
if (collection instanceof Set) {
return set((Set<E>) collection, mutex);
}
if (collection instanceof List) {
return list((List<E>) collection, mutex);
}
return collection(collection, mutex);
}
private static <E> Set<E> typePreservingSet(
Set<E> set, @Nullable Object mutex) {
if (set instanceof SortedSet) {
return sortedSet((SortedSet<E>) set, mutex);
} else {
return set(set, mutex);
}
}
private static class SynchronizedAsMapEntries<K, V>
extends SynchronizedSet<Map.Entry<K, Collection<V>>> {
SynchronizedAsMapEntries(
Set<Map.Entry<K, Collection<V>>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Map.Entry<K, Collection<V>>> iterator() {
// Must be manually synchronized.
final Iterator<Map.Entry<K, Collection<V>>> iterator = super.iterator();
return new ForwardingIterator<Map.Entry<K, Collection<V>>>() {
@Override protected Iterator<Map.Entry<K, Collection<V>>> delegate() {
return iterator;
}
@Override public Map.Entry<K, Collection<V>> next() {
final Map.Entry<K, Collection<V>> entry = super.next();
return new ForwardingMapEntry<K, Collection<V>>() {
@Override protected Map.Entry<K, Collection<V>> delegate() {
return entry;
}
@Override public Collection<V> getValue() {
return typePreservingCollection(entry.getValue(), mutex);
}
};
}
};
}
// See Collections.CheckedMap.CheckedEntrySet for details on attacks.
@Override public Object[] toArray() {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate());
}
}
@Override public <T> T[] toArray(T[] array) {
synchronized (mutex) {
return ObjectArrays.toArrayImpl(delegate(), array);
}
}
@Override public boolean contains(Object o) {
synchronized (mutex) {
return Maps.containsEntryImpl(delegate(), o);
}
}
@Override public boolean containsAll(Collection<?> c) {
synchronized (mutex) {
return Collections2.containsAllImpl(delegate(), c);
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return Sets.equalsImpl(delegate(), o);
}
}
@Override public boolean remove(Object o) {
synchronized (mutex) {
return Maps.removeEntryImpl(delegate(), o);
}
}
@Override public boolean removeAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.removeAll(delegate().iterator(), c);
}
}
@Override public boolean retainAll(Collection<?> c) {
synchronized (mutex) {
return Iterators.retainAll(delegate().iterator(), c);
}
}
private static final long serialVersionUID = 0;
}
@VisibleForTesting
static <K, V> Map<K, V> map(Map<K, V> map, @Nullable Object mutex) {
return new SynchronizedMap<K, V>(map, mutex);
}
private static class SynchronizedMap<K, V> extends SynchronizedObject
implements Map<K, V> {
transient Set<K> keySet;
transient Collection<V> values;
transient Set<Map.Entry<K, V>> entrySet;
SynchronizedMap(Map<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@SuppressWarnings("unchecked")
@Override Map<K, V> delegate() {
return (Map<K, V>) super.delegate();
}
@Override
public void clear() {
synchronized (mutex) {
delegate().clear();
}
}
@Override
public boolean containsKey(Object key) {
synchronized (mutex) {
return delegate().containsKey(key);
}
}
@Override
public boolean containsValue(Object value) {
synchronized (mutex) {
return delegate().containsValue(value);
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
synchronized (mutex) {
if (entrySet == null) {
entrySet = set(delegate().entrySet(), mutex);
}
return entrySet;
}
}
@Override
public V get(Object key) {
synchronized (mutex) {
return delegate().get(key);
}
}
@Override
public boolean isEmpty() {
synchronized (mutex) {
return delegate().isEmpty();
}
}
@Override
public Set<K> keySet() {
synchronized (mutex) {
if (keySet == null) {
keySet = set(delegate().keySet(), mutex);
}
return keySet;
}
}
@Override
public V put(K key, V value) {
synchronized (mutex) {
return delegate().put(key, value);
}
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
synchronized (mutex) {
delegate().putAll(map);
}
}
@Override
public V remove(Object key) {
synchronized (mutex) {
return delegate().remove(key);
}
}
@Override
public int size() {
synchronized (mutex) {
return delegate().size();
}
}
@Override
public Collection<V> values() {
synchronized (mutex) {
if (values == null) {
values = collection(delegate().values(), mutex);
}
return values;
}
}
@Override public boolean equals(Object o) {
if (o == this) {
return true;
}
synchronized (mutex) {
return delegate().equals(o);
}
}
@Override public int hashCode() {
synchronized (mutex) {
return delegate().hashCode();
}
}
private static final long serialVersionUID = 0;
}
static <K, V> SortedMap<K, V> sortedMap(
SortedMap<K, V> sortedMap, @Nullable Object mutex) {
return new SynchronizedSortedMap<K, V>(sortedMap, mutex);
}
static class SynchronizedSortedMap<K, V> extends SynchronizedMap<K, V>
implements SortedMap<K, V> {
SynchronizedSortedMap(SortedMap<K, V> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override SortedMap<K, V> delegate() {
return (SortedMap<K, V>) super.delegate();
}
@Override public Comparator<? super K> comparator() {
synchronized (mutex) {
return delegate().comparator();
}
}
@Override public K firstKey() {
synchronized (mutex) {
return delegate().firstKey();
}
}
@Override public SortedMap<K, V> headMap(K toKey) {
synchronized (mutex) {
return sortedMap(delegate().headMap(toKey), mutex);
}
}
@Override public K lastKey() {
synchronized (mutex) {
return delegate().lastKey();
}
}
@Override public SortedMap<K, V> subMap(K fromKey, K toKey) {
synchronized (mutex) {
return sortedMap(delegate().subMap(fromKey, toKey), mutex);
}
}
@Override public SortedMap<K, V> tailMap(K fromKey) {
synchronized (mutex) {
return sortedMap(delegate().tailMap(fromKey), mutex);
}
}
private static final long serialVersionUID = 0;
}
static <K, V> BiMap<K, V> biMap(BiMap<K, V> bimap, @Nullable Object mutex) {
if (bimap instanceof SynchronizedBiMap ||
bimap instanceof ImmutableBiMap) {
return bimap;
}
return new SynchronizedBiMap<K, V>(bimap, mutex, null);
}
@VisibleForTesting static class SynchronizedBiMap<K, V>
extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable {
private transient Set<V> valueSet;
private transient BiMap<V, K> inverse;
private SynchronizedBiMap(BiMap<K, V> delegate, @Nullable Object mutex,
@Nullable BiMap<V, K> inverse) {
super(delegate, mutex);
this.inverse = inverse;
}
@Override BiMap<K, V> delegate() {
return (BiMap<K, V>) super.delegate();
}
@Override public Set<V> values() {
synchronized (mutex) {
if (valueSet == null) {
valueSet = set(delegate().values(), mutex);
}
return valueSet;
}
}
@Override
public V forcePut(K key, V value) {
synchronized (mutex) {
return delegate().forcePut(key, value);
}
}
@Override
public BiMap<V, K> inverse() {
synchronized (mutex) {
if (inverse == null) {
inverse
= new SynchronizedBiMap<V, K>(delegate().inverse(), mutex, this);
}
return inverse;
}
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMap<K, V>
extends SynchronizedMap<K, Collection<V>> {
transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet;
transient Collection<Collection<V>> asMapValues;
SynchronizedAsMap(Map<K, Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Collection<V> get(Object key) {
synchronized (mutex) {
Collection<V> collection = super.get(key);
return (collection == null) ? null
: typePreservingCollection(collection, mutex);
}
}
@Override public Set<Map.Entry<K, Collection<V>>> entrySet() {
synchronized (mutex) {
if (asMapEntrySet == null) {
asMapEntrySet = new SynchronizedAsMapEntries<K, V>(
delegate().entrySet(), mutex);
}
return asMapEntrySet;
}
}
@Override public Collection<Collection<V>> values() {
synchronized (mutex) {
if (asMapValues == null) {
asMapValues
= new SynchronizedAsMapValues<V>(delegate().values(), mutex);
}
return asMapValues;
}
}
@Override public boolean containsValue(Object o) {
// values() and its contains() method are both synchronized.
return values().contains(o);
}
private static final long serialVersionUID = 0;
}
private static class SynchronizedAsMapValues<V>
extends SynchronizedCollection<Collection<V>> {
SynchronizedAsMapValues(
Collection<Collection<V>> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override public Iterator<Collection<V>> iterator() {
// Must be manually synchronized.
final Iterator<Collection<V>> iterator = super.iterator();
return new ForwardingIterator<Collection<V>>() {
@Override protected Iterator<Collection<V>> delegate() {
return iterator;
}
@Override public Collection<V> next() {
return typePreservingCollection(super.next(), mutex);
}
};
}
private static final long serialVersionUID = 0;
}
static <E> Queue<E> queue(Queue<E> queue, @Nullable Object mutex) {
return (queue instanceof SynchronizedQueue)
? queue
: new SynchronizedQueue<E>(queue, mutex);
}
private static class SynchronizedQueue<E> extends SynchronizedCollection<E>
implements Queue<E> {
SynchronizedQueue(Queue<E> delegate, @Nullable Object mutex) {
super(delegate, mutex);
}
@Override Queue<E> delegate() {
return (Queue<E>) super.delegate();
}
@Override
public E element() {
synchronized (mutex) {
return delegate().element();
}
}
@Override
public boolean offer(E e) {
synchronized (mutex) {
return delegate().offer(e);
}
}
@Override
public E peek() {
synchronized (mutex) {
return delegate().peek();
}
}
@Override
public E poll() {
synchronized (mutex) {
return delegate().poll();
}
}
@Override
public E remove() {
synchronized (mutex) {
return delegate().remove();
}
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Collections;
/**
* GWT emulation of {@link EmptyImmutableBiMap}.
*
* @author Hayward Chan
*/
@SuppressWarnings("serial")
final class EmptyImmutableBiMap extends ImmutableBiMap<Object, Object> {
static final EmptyImmutableBiMap INSTANCE = new EmptyImmutableBiMap();
private EmptyImmutableBiMap() {
super(Collections.emptyMap());
}
@Override public ImmutableBiMap<Object, Object> inverse() {
return this;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.EnumMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A {@code BiMap} backed by an {@code EnumMap} instance for keys-to-values, and
* a {@code HashMap} instance for values-to-keys. Null keys are not permitted,
* but null values are. An {@code EnumHashBiMap} and its inverse are both
* serializable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap">
* {@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class EnumHashBiMap<K extends Enum<K>, V>
extends AbstractBiMap<K, V> {
private transient Class<K> keyType;
/**
* Returns a new, empty {@code EnumHashBiMap} using the specified key type.
*
* @param keyType the key type
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Class<K> keyType) {
return new EnumHashBiMap<K, V>(keyType);
}
/**
* Constructs a new bimap with the same mappings as the specified map. If the
* specified map is an {@code EnumHashBiMap} or an {@link EnumBiMap}, the new
* bimap has the same key type as the input bimap. Otherwise, the specified
* map must contain at least one mapping, in order to determine the key type.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap} or an
* {@code EnumHashBiMap} instance and contains no mappings
*/
public static <K extends Enum<K>, V> EnumHashBiMap<K, V>
create(Map<K, ? extends V> map) {
EnumHashBiMap<K, V> bimap = create(EnumBiMap.inferKeyType(map));
bimap.putAll(map);
return bimap;
}
private EnumHashBiMap(Class<K> keyType) {
super(WellBehavedMap.wrap(
new EnumMap<K, V>(keyType)),
Maps.<V, K>newHashMapWithExpectedSize(
keyType.getEnumConstants().length));
this.keyType = keyType;
}
// Overriding these 3 methods to show that values may be null (but not keys)
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override public V put(K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(K key, @Nullable V value) {
return super.forcePut(key, value);
}
/** Returns the associated key type. */
public Class<K> keyType() {
return keyType;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset.Entry;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import javax.annotation.Nullable;
/**
* An immutable hash-based multiset. Does not permit null elements.
*
* <p>Its iterator orders elements according to the first appearance of the
* element among the items passed to the factory method or builder. When the
* multiset contains multiple instances of an element, those instances are
* consecutive in the iteration order.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(user): write an efficient asList() implementation
public abstract class ImmutableMultiset<E> extends ImmutableCollection<E>
implements Multiset<E> {
private static final ImmutableMultiset<Object> EMPTY =
new RegularImmutableMultiset<Object>(ImmutableMap.<Object, Integer>of(), 0);
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static <E> ImmutableMultiset<E> of() {
return (ImmutableMultiset<E>) EMPTY;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if {@code element} is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") // generic array created but never written
public static <E> ImmutableMultiset<E> of(E element) {
return copyOfInternal(element);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2) {
return copyOfInternal(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
return copyOfInternal(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
return copyOfInternal(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
return copyOfInternal(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static <E> ImmutableMultiset<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
return new Builder<E>()
.add(e1)
.add(e2)
.add(e3)
.add(e4)
.add(e5)
.add(e6)
.add(others)
.build();
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset
* with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 6.0
*/
public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
return copyOf(Arrays.asList(elements));
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
* a multiset with elements in the order {@code 2, 3, 3, 1}.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code elements}
* is an {@code ImmutableMultiset}, no copy will actually be performed, and
* the given multiset itself will be returned.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(
Iterable<? extends E> elements) {
if (elements instanceof ImmutableMultiset) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
if (!result.isPartialView()) {
return result;
}
}
Multiset<? extends E> multiset = (elements instanceof Multiset)
? Multisets.cast(elements)
: LinkedHashMultiset.create(elements);
return copyOfInternal(multiset);
}
private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
return copyOf(Arrays.asList(elements));
}
private static <E> ImmutableMultiset<E> copyOfInternal(
Multiset<? extends E> multiset) {
return copyFromEntries(multiset.entrySet());
}
static <E> ImmutableMultiset<E> copyFromEntries(
Collection<? extends Entry<? extends E>> entries) {
long size = 0;
ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder();
for (Entry<? extends E> entry : entries) {
int count = entry.getCount();
if (count > 0) {
// Since ImmutableMap.Builder throws an NPE if an element is null, no
// other null checks are needed.
builder.put(entry.getElement(), count);
size += count;
}
}
if (size == 0) {
return of();
}
return new RegularImmutableMultiset<E>(
builder.build(), Ints.saturatedCast(size));
}
/**
* Returns an immutable multiset containing the given elements.
*
* <p>The multiset is ordered by the first occurrence of each element. For
* example,
* {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
* yields a multiset with elements in the order {@code 2, 3, 3, 1}.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableMultiset<E> copyOf(
Iterator<? extends E> elements) {
Multiset<E> multiset = LinkedHashMultiset.create();
Iterators.addAll(multiset, elements);
return copyOfInternal(multiset);
}
ImmutableMultiset() {}
@Override public UnmodifiableIterator<E> iterator() {
final Iterator<Entry<E>> entryIterator = entrySet().iterator();
return new UnmodifiableIterator<E>() {
int remaining;
E element;
@Override
public boolean hasNext() {
return (remaining > 0) || entryIterator.hasNext();
}
@Override
public E next() {
if (remaining <= 0) {
Entry<E> entry = entryIterator.next();
element = entry.getElement();
remaining = entry.getCount();
}
remaining--;
return element;
}
};
}
@Override
public boolean contains(@Nullable Object object) {
return count(object) > 0;
}
@Override
public boolean containsAll(Collection<?> targets) {
return elementSet().containsAll(targets);
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@Override public boolean equals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
@Override public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override public String toString() {
return entrySet().toString();
}
private transient ImmutableSet<Entry<E>> entrySet;
@Override
public ImmutableSet<Entry<E>> entrySet() {
ImmutableSet<Entry<E>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
private final ImmutableSet<Entry<E>> createEntrySet() {
return isEmpty() ? ImmutableSet.<Entry<E>>of() : new EntrySet();
}
abstract Entry<E> getEntry(int index);
private final class EntrySet extends ImmutableSet<Entry<E>> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
public UnmodifiableIterator<Entry<E>> iterator() {
return asList().iterator();
}
@Override
ImmutableList<Entry<E>> createAsList() {
return new ImmutableAsList<Entry<E>>() {
@Override
public Entry<E> get(int index) {
return getEntry(index);
}
@Override
ImmutableCollection<Entry<E>> delegateCollection() {
return EntrySet.this;
}
};
}
@Override
public int size() {
return elementSet().size();
}
@Override
public boolean contains(Object o) {
if (o instanceof Entry) {
Entry<?> entry = (Entry<?>) o;
if (entry.getCount() <= 0) {
return false;
}
int count = count(entry.getElement());
return count == entry.getCount();
}
return false;
}
@Override
public int hashCode() {
return ImmutableMultiset.this.hashCode();
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
// TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
Object writeReplace() {
return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
}
private static final long serialVersionUID = 0;
}
static class EntrySetSerializedForm<E> implements Serializable {
final ImmutableMultiset<E> multiset;
EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
private static class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
SerializedForm(Multiset<?> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry<?> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset<Object> multiset =
LinkedHashMultiset.create(elements.length);
for (int i = 0; i < elements.length; i++) {
multiset.add(elements[i], counts[i]);
}
return ImmutableMultiset.copyOf(multiset);
}
private static final long serialVersionUID = 0;
}
// We can't label this with @Override, because it doesn't override anything
// in the GWT emulated version.
Object writeReplace() {
return new SerializedForm(this);
}
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <E> Builder<E> builder() {
return new Builder<E>();
}
/**
* A builder for creating immutable multiset instances, especially {@code
* public static final} multisets ("constant multisets"). Example:
* <pre> {@code
*
* public static final ImmutableMultiset<Bean> BEANS =
* new ImmutableMultiset.Builder<Bean>()
* .addCopies(Bean.COCOA, 4)
* .addCopies(Bean.GARDEN, 6)
* .addCopies(Bean.RED, 8)
* .addCopies(Bean.BLACK_EYED, 10)
* .build();}</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multisets in series.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<E> extends ImmutableCollection.Builder<E> {
final Multiset<E> contents;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultiset#builder}.
*/
public Builder() {
this(LinkedHashMultiset.<E>create());
}
Builder(Multiset<E> contents) {
this.contents = contents;
}
/**
* Adds {@code element} to the {@code ImmutableMultiset}.
*
* @param element the element to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
*/
@Override public Builder<E> add(E element) {
contents.add(checkNotNull(element));
return this;
}
/**
* Adds a number of occurrences of an element to this {@code
* ImmutableMultiset}.
*
* @param element the element to add
* @param occurrences the number of occurrences of the element to add. May
* be zero, in which case no change will be made.
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code occurrences} is negative, or
* if this operation would result in more than {@link Integer#MAX_VALUE}
* occurrences of the element
*/
public Builder<E> addCopies(E element, int occurrences) {
contents.add(checkNotNull(element), occurrences);
return this;
}
/**
* Adds or removes the necessary occurrences of an element such that the
* element attains the desired count.
*
* @param element the element to add or remove occurrences of
* @param count the desired count of the element in this multiset
* @return this {@code Builder} object
* @throws NullPointerException if {@code element} is null
* @throws IllegalArgumentException if {@code count} is negative
*/
public Builder<E> setCount(E element, int count) {
contents.setCount(checkNotNull(element), count);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> add(E... elements) {
super.add(elements);
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the {@code Iterable} to add to the {@code
* ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterable<? extends E> elements) {
if (elements instanceof Multiset) {
Multiset<? extends E> multiset = Multisets.cast(elements);
for (Entry<? extends E> entry : multiset.entrySet()) {
addCopies(entry.getElement(), entry.getCount());
}
} else {
super.addAll(elements);
}
return this;
}
/**
* Adds each element of {@code elements} to the {@code ImmutableMultiset}.
*
* @param elements the elements to add to the {@code ImmutableMultiset}
* @return this {@code Builder} object
* @throws NullPointerException if {@code elements} is null or contains a
* null element
*/
@Override public Builder<E> addAll(Iterator<? extends E> elements) {
super.addAll(elements);
return this;
}
/**
* Returns a newly-created {@code ImmutableMultiset} based on the contents
* of the {@code Builder}.
*/
@Override public ImmutableMultiset<E> build() {
return copyOf(contents);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps.EntryTransformer;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Provides static methods acting on or generating a {@code Multimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multimaps">
* {@code Multimaps}</a>.
*
* @author Jared Levy
* @author Robert Konigsberg
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Multimaps {
private Multimaps() {}
/**
* Creates a new {@code Multimap} backed by {@code map}, whose internal value
* collections are generated by {@code factory}.
*
* <b>Warning: do not use</b> this method when the collections returned by
* {@code factory} implement either {@link List} or {@code Set}! Use the more
* specific method {@link #newListMultimap}, {@link #newSetMultimap} or {@link
* #newSortedSetMultimap} instead, to avoid very surprising behavior from
* {@link Multimap#equals}.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* collections generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()}, {@link HashMultimap#create()},
* {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the collections returned by {@code factory}. Those objects should not be
* manually updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty collections that will each hold all
* values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> Multimap<K, V> newMultimap(Map<K, Collection<V>> map,
final Supplier<? extends Collection<V>> factory) {
return new CustomMultimap<K, V>(map, factory);
}
private static class CustomMultimap<K, V> extends AbstractMapBasedMultimap<K, V> {
transient Supplier<? extends Collection<V>> factory;
CustomMultimap(Map<K, Collection<V>> map,
Supplier<? extends Collection<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Collection<V> createCollection() {
return factory.get();
}
// can't use Serialization writeMultimap and populateMultimap methods since
// there's no way to generate the empty backing map.
}
/**
* Creates a new {@code ListMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link List}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. The multimap's {@code get}, {@code
* removeAll}, and {@code replaceValues} methods return {@code RandomAccess}
* lists if the factory does. However, the multimap's {@code get} method
* returns instances of a different class than does {@code factory.get()}.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* lists generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedListMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()}
* won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the lists returned by {@code factory}. Those objects should not be manually
* updated, they should be empty when provided, and they should not use soft,
* weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty lists that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> ListMultimap<K, V> newListMultimap(
Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) {
return new CustomListMultimap<K, V>(map, factory);
}
private static class CustomListMultimap<K, V>
extends AbstractListMultimap<K, V> {
transient Supplier<? extends List<V>> factory;
CustomListMultimap(Map<K, Collection<V>> map,
Supplier<? extends List<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected List<V> createCollection() {
return factory.get();
}
}
/**
* Creates a new {@code SetMultimap} that uses the provided map and factory.
* It can generate a multimap based on arbitrary {@link Map} and {@link Set}
* classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link HashMultimap#create()}, {@link LinkedHashMultimap#create()},
* {@link TreeMultimap#create()}, and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sets that will each hold all values
* for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SetMultimap<K, V> newSetMultimap(
Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) {
return new CustomSetMultimap<K, V>(map, factory);
}
private static class CustomSetMultimap<K, V>
extends AbstractSetMultimap<K, V> {
transient Supplier<? extends Set<V>> factory;
CustomSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends Set<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
}
@Override protected Set<V> createCollection() {
return factory.get();
}
}
/**
* Creates a new {@code SortedSetMultimap} that uses the provided map and
* factory. It can generate a multimap based on arbitrary {@link Map} and
* {@link SortedSet} classes.
*
* <p>The {@code factory}-generated and {@code map} classes determine the
* multimap iteration order. They also specify the behavior of the
* {@code equals}, {@code hashCode}, and {@code toString} methods for the
* multimap and its returned views. However, the multimap's {@code get}
* method returns instances of a different class than {@code factory.get()}
* does.
*
* <p>The multimap is serializable if {@code map}, {@code factory}, the
* sets generated by {@code factory}, and the multimap contents are all
* serializable.
*
* <p>The multimap is not threadsafe when any concurrent operations update the
* multimap, even if {@code map} and the instances generated by
* {@code factory} are. Concurrent read operations will work correctly. To
* allow concurrent update operations, wrap the multimap with a call to
* {@link #synchronizedSortedSetMultimap}.
*
* <p>Call this method only when the simpler methods
* {@link TreeMultimap#create()} and
* {@link TreeMultimap#create(Comparator, Comparator)} won't suffice.
*
* <p>Note: the multimap assumes complete ownership over of {@code map} and
* the sets returned by {@code factory}. Those objects should not be manually
* updated and they should not use soft, weak, or phantom references.
*
* @param map place to store the mapping from each key to its corresponding
* values
* @param factory supplier of new, empty sorted sets that will each hold
* all values for a given key
* @throws IllegalArgumentException if {@code map} is not empty
*/
public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap(
Map<K, Collection<V>> map,
final Supplier<? extends SortedSet<V>> factory) {
return new CustomSortedSetMultimap<K, V>(map, factory);
}
private static class CustomSortedSetMultimap<K, V>
extends AbstractSortedSetMultimap<K, V> {
transient Supplier<? extends SortedSet<V>> factory;
transient Comparator<? super V> valueComparator;
CustomSortedSetMultimap(Map<K, Collection<V>> map,
Supplier<? extends SortedSet<V>> factory) {
super(map);
this.factory = checkNotNull(factory);
valueComparator = factory.get().comparator();
}
@Override protected SortedSet<V> createCollection() {
return factory.get();
}
@Override public Comparator<? super V> valueComparator() {
return valueComparator;
}
}
/**
* Copies each key-value mapping in {@code source} into {@code dest}, with
* its key and value reversed.
*
* <p>If {@code source} is an {@link ImmutableMultimap}, consider using
* {@link ImmutableMultimap#inverse} instead.
*
* @param source any multimap
* @param dest the multimap to copy into; usually empty
* @return {@code dest}
*/
public static <K, V, M extends Multimap<K, V>> M invertFrom(
Multimap<? extends V, ? extends K> source, M dest) {
checkNotNull(dest);
for (Map.Entry<? extends V, ? extends K> entry : source.entries()) {
dest.put(entry.getValue(), entry.getKey());
}
return dest;
}
/**
* Returns a synchronized (thread-safe) multimap backed by the specified
* multimap. In order to guarantee serial access, it is critical that
* <b>all</b> access to the backing multimap is accomplished through the
* returned multimap.
*
* <p>It is imperative that the user manually synchronize on the returned
* multimap when accessing any of its collection views: <pre> {@code
*
* Multimap<K, V> multimap = Multimaps.synchronizedMultimap(
* HashMultimap.<K, V>create());
* ...
* Collection<V> values = multimap.get(key); // Needn't be in synchronized block
* ...
* synchronized (multimap) { // Synchronizing on multimap, not values!
* Iterator<V> i = values.iterator(); // Must be in synchronized block
* while (i.hasNext()) {
* foo(i.next());
* }
* }}</pre>
*
* <p>Failure to follow this advice may result in non-deterministic behavior.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that aren't
* synchronized.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped in a synchronized view
* @return a synchronized view of the specified multimap
*/
public static <K, V> Multimap<K, V> synchronizedMultimap(
Multimap<K, V> multimap) {
return Synchronized.multimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified multimap. Query operations on
* the returned multimap "read through" to the specified multimap, and
* attempts to modify the returned multimap, either directly or through the
* multimap's views, result in an {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> Multimap<K, V> unmodifiableMultimap(
Multimap<K, V> delegate) {
if (delegate instanceof UnmodifiableMultimap ||
delegate instanceof ImmutableMultimap) {
return delegate;
}
return new UnmodifiableMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap(
ImmutableMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
private static class UnmodifiableMultimap<K, V>
extends ForwardingMultimap<K, V> implements Serializable {
final Multimap<K, V> delegate;
transient Collection<Entry<K, V>> entries;
transient Multiset<K> keys;
transient Set<K> keySet;
transient Collection<V> values;
transient Map<K, Collection<V>> map;
UnmodifiableMultimap(final Multimap<K, V> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override protected Multimap<K, V> delegate() {
return delegate;
}
@Override public void clear() {
throw new UnsupportedOperationException();
}
@Override public Map<K, Collection<V>> asMap() {
Map<K, Collection<V>> result = map;
if (result == null) {
result = map = Collections.unmodifiableMap(
Maps.transformValues(delegate.asMap(), new Function<Collection<V>, Collection<V>>() {
@Override
public Collection<V> apply(Collection<V> collection) {
return unmodifiableValueCollection(collection);
}
}));
}
return result;
}
@Override public Collection<Entry<K, V>> entries() {
Collection<Entry<K, V>> result = entries;
if (result == null) {
entries = result = unmodifiableEntries(delegate.entries());
}
return result;
}
@Override public Collection<V> get(K key) {
return unmodifiableValueCollection(delegate.get(key));
}
@Override public Multiset<K> keys() {
Multiset<K> result = keys;
if (result == null) {
keys = result = Multisets.unmodifiableMultiset(delegate.keys());
}
return result;
}
@Override public Set<K> keySet() {
Set<K> result = keySet;
if (result == null) {
keySet = result = Collections.unmodifiableSet(delegate.keySet());
}
return result;
}
@Override public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override public Collection<V> values() {
Collection<V> result = values;
if (result == null) {
values = result = Collections.unmodifiableCollection(delegate.values());
}
return result;
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableListMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> {
UnmodifiableListMultimap(ListMultimap<K, V> delegate) {
super(delegate);
}
@Override public ListMultimap<K, V> delegate() {
return (ListMultimap<K, V>) super.delegate();
}
@Override public List<V> get(K key) {
return Collections.unmodifiableList(delegate().get(key));
}
@Override public List<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public List<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSetMultimap<K, V>
extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> {
UnmodifiableSetMultimap(SetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SetMultimap<K, V> delegate() {
return (SetMultimap<K, V>) super.delegate();
}
@Override public Set<V> get(K key) {
/*
* Note that this doesn't return a SortedSet when delegate is a
* SortedSetMultiset, unlike (SortedSet<V>) super.get().
*/
return Collections.unmodifiableSet(delegate().get(key));
}
@Override public Set<Map.Entry<K, V>> entries() {
return Maps.unmodifiableEntrySet(delegate().entries());
}
@Override public Set<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public Set<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
private static final long serialVersionUID = 0;
}
private static class UnmodifiableSortedSetMultimap<K, V>
extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> {
UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) {
super(delegate);
}
@Override public SortedSetMultimap<K, V> delegate() {
return (SortedSetMultimap<K, V>) super.delegate();
}
@Override public SortedSet<V> get(K key) {
return Collections.unmodifiableSortedSet(delegate().get(key));
}
@Override public SortedSet<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super V> valueComparator() {
return delegate().valueComparator();
}
private static final long serialVersionUID = 0;
}
/**
* Returns a synchronized (thread-safe) {@code SetMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> synchronizedSetMultimap(
SetMultimap<K, V> multimap) {
return Synchronized.setMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SetMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
SetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSetMultimap ||
delegate instanceof ImmutableSetMultimap) {
return delegate;
}
return new UnmodifiableSetMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(
ImmutableSetMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by
* the specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V>
synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) {
return Synchronized.sortedSetMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code SortedSetMultimap}.
* Query operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(
SortedSetMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableSortedSetMultimap) {
return delegate;
}
return new UnmodifiableSortedSetMultimap<K, V>(delegate);
}
/**
* Returns a synchronized (thread-safe) {@code ListMultimap} backed by the
* specified multimap.
*
* <p>You must follow the warnings described in {@link #synchronizedMultimap}.
*
* @param multimap the multimap to be wrapped
* @return a synchronized view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> synchronizedListMultimap(
ListMultimap<K, V> multimap) {
return Synchronized.listMultimap(multimap, null);
}
/**
* Returns an unmodifiable view of the specified {@code ListMultimap}. Query
* operations on the returned multimap "read through" to the specified
* multimap, and attempts to modify the returned multimap, either directly or
* through the multimap's views, result in an
* {@code UnsupportedOperationException}.
*
* <p>Note that the generated multimap's {@link Multimap#removeAll} and
* {@link Multimap#replaceValues} methods return collections that are
* modifiable.
*
* <p>The returned multimap will be serializable if the specified multimap is
* serializable.
*
* @param delegate the multimap for which an unmodifiable view is to be
* returned
* @return an unmodifiable view of the specified multimap
*/
public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ListMultimap<K, V> delegate) {
if (delegate instanceof UnmodifiableListMultimap ||
delegate instanceof ImmutableListMultimap) {
return delegate;
}
return new UnmodifiableListMultimap<K, V>(delegate);
}
/**
* Simply returns its argument.
*
* @deprecated no need to use this
* @since 10.0
*/
@Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(
ImmutableListMultimap<K, V> delegate) {
return checkNotNull(delegate);
}
/**
* Returns an unmodifiable view of the specified collection, preserving the
* interface for instances of {@code SortedSet}, {@code Set}, {@code List} and
* {@code Collection}, in that order of preference.
*
* @param collection the collection for which to return an unmodifiable view
* @return an unmodifiable view of the collection
*/
private static <V> Collection<V> unmodifiableValueCollection(
Collection<V> collection) {
if (collection instanceof SortedSet) {
return Collections.unmodifiableSortedSet((SortedSet<V>) collection);
} else if (collection instanceof Set) {
return Collections.unmodifiableSet((Set<V>) collection);
} else if (collection instanceof List) {
return Collections.unmodifiableList((List<V>) collection);
}
return Collections.unmodifiableCollection(collection);
}
/**
* Returns an unmodifiable view of the specified collection of entries. The
* {@link Entry#setValue} operation throws an {@link
* UnsupportedOperationException}. If the specified collection is a {@code
* Set}, the returned collection is also a {@code Set}.
*
* @param entries the entries for which to return an unmodifiable view
* @return an unmodifiable view of the entries
*/
private static <K, V> Collection<Entry<K, V>> unmodifiableEntries(
Collection<Entry<K, V>> entries) {
if (entries instanceof Set) {
return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries);
}
return new Maps.UnmodifiableEntries<K, V>(
Collections.unmodifiableCollection(entries));
}
/**
* Returns {@link ListMultimap#asMap multimap.asMap()}, with its type
* corrected from {@code Map<K, Collection<V>>} to {@code Map<K, List<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of ListMultimap.asMap()
public static <K, V> Map<K, List<V>> asMap(ListMultimap<K, V> multimap) {
return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected
* from {@code Map<K, Collection<V>>} to {@code Map<K, Set<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of SetMultimap.asMap()
public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) {
return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type
* corrected from {@code Map<K, Collection<V>>} to
* {@code Map<K, SortedSet<V>>}.
*
* @since 15.0
*/
@Beta
@SuppressWarnings("unchecked")
// safe by specification of SortedSetMultimap.asMap()
public static <K, V> Map<K, SortedSet<V>> asMap(
SortedSetMultimap<K, V> multimap) {
return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap();
}
/**
* Returns {@link Multimap#asMap multimap.asMap()}. This is provided for
* parity with the other more strongly-typed {@code asMap()} implementations.
*
* @since 15.0
*/
@Beta
public static <K, V> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) {
return multimap.asMap();
}
/**
* Returns a multimap view of the specified map. The multimap is backed by the
* map, so changes to the map are reflected in the multimap, and vice versa.
* If the map is modified while an iteration over one of the multimap's
* collection views is in progress (except through the iterator's own {@code
* remove} operation, or through the {@code setValue} operation on a map entry
* returned by the iterator), the results of the iteration are undefined.
*
* <p>The multimap supports mapping removal, which removes the corresponding
* mapping from the map. It does not support any operations which might add
* mappings, such as {@code put}, {@code putAll} or {@code replaceValues}.
*
* <p>The returned multimap will be serializable if the specified map is
* serializable.
*
* @param map the backing map for the returned multimap view
*/
public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) {
return new MapMultimap<K, V>(map);
}
/** @see Multimaps#forMap */
private static class MapMultimap<K, V>
extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable {
final Map<K, V> map;
MapMultimap(Map<K, V> map) {
this.map = checkNotNull(map);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public boolean containsEntry(Object key, Object value) {
return map.entrySet().contains(Maps.immutableEntry(key, value));
}
@Override
public Set<V> get(final K key) {
return new Sets.ImprovedAbstractSet<V>() {
@Override public Iterator<V> iterator() {
return new Iterator<V>() {
int i;
@Override
public boolean hasNext() {
return (i == 0) && map.containsKey(key);
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
i++;
return map.get(key);
}
@Override
public void remove() {
checkState(i == 1);
i = -1;
map.remove(key);
}
};
}
@Override public int size() {
return map.containsKey(key) ? 1 : 0;
}
};
}
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
return map.entrySet().remove(Maps.immutableEntry(key, value));
}
@Override
public Set<V> removeAll(Object key) {
Set<V> values = new HashSet<V>(2);
if (!map.containsKey(key)) {
return values;
}
values.add(map.remove(key));
return values;
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<K> keySet() {
return map.keySet();
}
@Override
public Collection<V> values() {
return map.values();
}
@Override
public Set<Entry<K, V>> entries() {
return map.entrySet();
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return map.entrySet().iterator();
}
@Override
Map<K, Collection<V>> createAsMap() {
return new AsMap<K, V>(this);
}
@Override public int hashCode() {
return map.hashCode();
}
private static final long serialVersionUID = 7845222491160860175L;
}
/**
* Returns a view of a multimap where each value is transformed by a function.
* All other properties of the multimap, such as iteration order, are left
* intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
* Function<Integer, String> square = new Function<Integer, String>() {
* public String apply(Integer in) {
* return Integer.toString(in * in);
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformValues(multimap, square);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformValues(
Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function);
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a multimap whose values are derived from the original
* multimap's entries. In contrast to {@link #transformValues}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* SetMultimap<String, Integer> multimap =
* ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return (value >= 0) ? key : "no" + key;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[a, a], b=[nob]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is. The {@code equals} and {@code hashCode} methods
* of the returned multimap are meaningless, since there is not a definition
* of {@code equals} or {@code hashCode} for general collections, and
* {@code get()} will return a general {@code Collection} as opposed to a
* {@code List} or a {@code Set}.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> Multimap<K, V2> transformEntries(
Multimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesMultimap<K, V1, V2>(fromMap, transformer);
}
private static class TransformedEntriesMultimap<K, V1, V2>
extends AbstractMultimap<K, V2> {
final Multimap<K, V1> fromMultimap;
final EntryTransformer<? super K, ? super V1, V2> transformer;
TransformedEntriesMultimap(Multimap<K, V1> fromMultimap,
final EntryTransformer<? super K, ? super V1, V2> transformer) {
this.fromMultimap = checkNotNull(fromMultimap);
this.transformer = checkNotNull(transformer);
}
Collection<V2> transform(K key, Collection<V1> values) {
Function<? super V1, V2> function =
Maps.asValueToValueFunction(transformer, key);
if (values instanceof List) {
return Lists.transform((List<V1>) values, function);
} else {
return Collections2.transform(values, function);
}
}
@Override
Map<K, Collection<V2>> createAsMap() {
return Maps.transformEntries(fromMultimap.asMap(),
new EntryTransformer<K, Collection<V1>, Collection<V2>>() {
@Override public Collection<V2> transformEntry(
K key, Collection<V1> value) {
return transform(key, value);
}
});
}
@Override public void clear() {
fromMultimap.clear();
}
@Override public boolean containsKey(Object key) {
return fromMultimap.containsKey(key);
}
@Override
Iterator<Entry<K, V2>> entryIterator() {
return Iterators.transform(fromMultimap.entries().iterator(),
Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
}
@Override public Collection<V2> get(final K key) {
return transform(key, fromMultimap.get(key));
}
@Override public boolean isEmpty() {
return fromMultimap.isEmpty();
}
@Override public Set<K> keySet() {
return fromMultimap.keySet();
}
@Override public Multiset<K> keys() {
return fromMultimap.keys();
}
@Override public boolean put(K key, V2 value) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public boolean putAll(
Multimap<? extends K, ? extends V2> multimap) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean remove(Object key, Object value) {
return get((K) key).remove(value);
}
@SuppressWarnings("unchecked")
@Override public Collection<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public Collection<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
@Override public int size() {
return fromMultimap.size();
}
@Override
Collection<V2> createValues() {
return Collections2.transform(
fromMultimap.entries(), Maps.<K, V1, V2>asEntryToValueFunction(transformer));
}
}
/**
* Returns a view of a {@code ListMultimap} where each value is transformed by
* a function. All other properties of the multimap, such as iteration order,
* are left intact. For example, the code: <pre> {@code
*
* ListMultimap<String, Integer> multimap
* = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
* Function<Integer, Double> sqrt =
* new Function<Integer, Double>() {
* public Double apply(Integer in) {
* return Math.sqrt((int) in);
* }
* };
* ListMultimap<String, Double> transformed = Multimaps.transformValues(map,
* sqrt);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {a=[2.0, 4.0], b=[3.0]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys, and
* even null values provided that the function is capable of accepting null
* input. The transformed multimap might contain null values, if the function
* sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The function is applied lazily, invoked when needed. This is necessary
* for the returned multimap to be a view, but it means that the function will
* be applied many times for bulk operations like
* {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to
* perform well, {@code function} should be fast. To avoid lazy evaluation
* when the returned multimap doesn't need to be a view, copy the returned
* multimap into a new multimap of your choosing.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformValues(
ListMultimap<K, V1> fromMultimap,
final Function<? super V1, V2> function) {
checkNotNull(function);
EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function);
return transformEntries(fromMultimap, transformer);
}
/**
* Returns a view of a {@code ListMultimap} whose values are derived from the
* original multimap's entries. In contrast to
* {@link #transformValues(ListMultimap, Function)}, this method's
* entry-transformation logic may depend on the key as well as the value.
*
* <p>All other properties of the transformed multimap, such as iteration
* order, are left intact. For example, the code: <pre> {@code
*
* Multimap<String, Integer> multimap =
* ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
* EntryTransformer<String, Integer, String> transformer =
* new EntryTransformer<String, Integer, String>() {
* public String transformEntry(String key, Integer value) {
* return key + value;
* }
* };
* Multimap<String, String> transformed =
* Multimaps.transformEntries(multimap, transformer);
* System.out.println(transformed);}</pre>
*
* ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}.
*
* <p>Changes in the underlying multimap are reflected in this view.
* Conversely, this view supports removal operations, and these are reflected
* in the underlying multimap.
*
* <p>It's acceptable for the underlying multimap to contain null keys and
* null values provided that the transformer is capable of accepting null
* inputs. The transformed multimap might contain null values if the
* transformer sometimes gives a null result.
*
* <p>The returned multimap is not thread-safe or serializable, even if the
* underlying multimap is.
*
* <p>The transformer is applied lazily, invoked when needed. This is
* necessary for the returned multimap to be a view, but it means that the
* transformer will be applied many times for bulk operations like {@link
* Multimap#containsValue} and {@link Object#toString}. For this to perform
* well, {@code transformer} should be fast. To avoid lazy evaluation when the
* returned multimap doesn't need to be a view, copy the returned multimap
* into a new multimap of your choosing.
*
* <p><b>Warning:</b> This method assumes that for any instance {@code k} of
* {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies
* that {@code k2} is also of type {@code K}. Using an {@code
* EntryTransformer} key type for which this may not hold, such as {@code
* ArrayList}, may risk a {@code ClassCastException} when calling methods on
* the transformed multimap.
*
* @since 7.0
*/
public static <K, V1, V2> ListMultimap<K, V2> transformEntries(
ListMultimap<K, V1> fromMap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
return new TransformedEntriesListMultimap<K, V1, V2>(fromMap, transformer);
}
private static final class TransformedEntriesListMultimap<K, V1, V2>
extends TransformedEntriesMultimap<K, V1, V2>
implements ListMultimap<K, V2> {
TransformedEntriesListMultimap(ListMultimap<K, V1> fromMultimap,
EntryTransformer<? super K, ? super V1, V2> transformer) {
super(fromMultimap, transformer);
}
@Override List<V2> transform(K key, Collection<V1> values) {
return Lists.transform((List<V1>) values, Maps.asValueToValueFunction(transformer, key));
}
@Override public List<V2> get(K key) {
return transform(key, fromMultimap.get(key));
}
@SuppressWarnings("unchecked")
@Override public List<V2> removeAll(Object key) {
return transform((K) key, fromMultimap.removeAll(key));
}
@Override public List<V2> replaceValues(
K key, Iterable<? extends V2> values) {
throw new UnsupportedOperationException();
}
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterable} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterable. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys, stringLengthFunction);
* System.out.println(index);}</pre>
*
* <p>prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* <p>The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterable<V> values, Function<? super V, K> keyFunction) {
return index(values.iterator(), keyFunction);
}
/**
* Creates an index {@code ImmutableListMultimap} that contains the results of
* applying a specified function to each item in an {@code Iterator} of
* values. Each value will be stored as a value in the resulting multimap,
* yielding a multimap with the same size as the input iterator. The key used
* to store that value in the multimap will be the result of calling the
* function on that value. The resulting multimap is created as an immutable
* snapshot. In the returned multimap, keys appear in the order they are first
* encountered, and the values corresponding to each key appear in the same
* order as they are encountered.
*
* <p>For example, <pre> {@code
*
* List<String> badGuys =
* Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
* Function<String, Integer> stringLengthFunction = ...;
* Multimap<Integer, String> index =
* Multimaps.index(badGuys.iterator(), stringLengthFunction);
* System.out.println(index);}</pre>
*
* <p>prints <pre> {@code
*
* {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}}</pre>
*
* <p>The returned multimap is serializable if its keys and values are all
* serializable.
*
* @param values the values to use when constructing the {@code
* ImmutableListMultimap}
* @param keyFunction the function used to produce the key for each value
* @return {@code ImmutableListMultimap} mapping the result of evaluating the
* function {@code keyFunction} on each value in the input collection to
* that value
* @throws NullPointerException if any of the following cases is true:
* <ul>
* <li>{@code values} is null
* <li>{@code keyFunction} is null
* <li>An element in {@code values} is null
* <li>{@code keyFunction} returns {@code null} for any element of {@code
* values}
* </ul>
* @since 10.0
*/
public static <K, V> ImmutableListMultimap<K, V> index(
Iterator<V> values, Function<? super V, K> keyFunction) {
checkNotNull(keyFunction);
ImmutableListMultimap.Builder<K, V> builder
= ImmutableListMultimap.builder();
while (values.hasNext()) {
V value = values.next();
checkNotNull(value, values);
builder.put(keyFunction.apply(value), value);
}
return builder.build();
}
static class Keys<K, V> extends AbstractMultiset<K> {
final Multimap<K, V> multimap;
Keys(Multimap<K, V> multimap) {
this.multimap = multimap;
}
@Override Iterator<Multiset.Entry<K>> entryIterator() {
return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>(
multimap.asMap().entrySet().iterator()) {
@Override
Multiset.Entry<K> transform(
final Map.Entry<K, Collection<V>> backingEntry) {
return new Multisets.AbstractEntry<K>() {
@Override
public K getElement() {
return backingEntry.getKey();
}
@Override
public int getCount() {
return backingEntry.getValue().size();
}
};
}
};
}
@Override int distinctElements() {
return multimap.asMap().size();
}
@Override Set<Multiset.Entry<K>> createEntrySet() {
return new KeysEntrySet();
}
class KeysEntrySet extends Multisets.EntrySet<K> {
@Override Multiset<K> multiset() {
return Keys.this;
}
@Override public Iterator<Multiset.Entry<K>> iterator() {
return entryIterator();
}
@Override public int size() {
return distinctElements();
}
@Override public boolean isEmpty() {
return multimap.isEmpty();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap.asMap().get(entry.getElement());
return collection != null && collection.size() == entry.getCount();
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) o;
Collection<V> collection = multimap.asMap().get(entry.getElement());
if (collection != null && collection.size() == entry.getCount()) {
collection.clear();
return true;
}
}
return false;
}
}
@Override public boolean contains(@Nullable Object element) {
return multimap.containsKey(element);
}
@Override public Iterator<K> iterator() {
return Maps.keyIterator(multimap.entries().iterator());
}
@Override public int count(@Nullable Object element) {
Collection<V> values = Maps.safeGet(multimap.asMap(), element);
return (values == null) ? 0 : values.size();
}
@Override public int remove(@Nullable Object element, int occurrences) {
checkArgument(occurrences >= 0);
if (occurrences == 0) {
return count(element);
}
Collection<V> values = Maps.safeGet(multimap.asMap(), element);
if (values == null) {
return 0;
}
int oldCount = values.size();
if (occurrences >= oldCount) {
values.clear();
} else {
Iterator<V> iterator = values.iterator();
for (int i = 0; i < occurrences; i++) {
iterator.next();
iterator.remove();
}
}
return oldCount;
}
@Override public void clear() {
multimap.clear();
}
@Override public Set<K> elementSet() {
return multimap.keySet();
}
}
/**
* A skeleton implementation of {@link Multimap#entries()}.
*/
abstract static class Entries<K, V> extends
AbstractCollection<Map.Entry<K, V>> {
abstract Multimap<K, V> multimap();
@Override public int size() {
return multimap().size();
}
@Override public boolean contains(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
@Override public boolean remove(@Nullable Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
return multimap().remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override public void clear() {
multimap().clear();
}
}
/**
* A skeleton implementation of {@link Multimap#asMap()}.
*/
static final class AsMap<K, V> extends
Maps.ImprovedAbstractMap<K, Collection<V>> {
private final Multimap<K, V> multimap;
AsMap(Multimap<K, V> multimap) {
this.multimap = checkNotNull(multimap);
}
@Override public int size() {
return multimap.keySet().size();
}
@Override protected Set<Entry<K, Collection<V>>> createEntrySet() {
return new EntrySet();
}
void removeValuesForKey(Object key) {
multimap.keySet().remove(key);
}
class EntrySet extends Maps.EntrySet<K, Collection<V>> {
@Override Map<K, Collection<V>> map() {
return AsMap.this;
}
@Override public Iterator<Entry<K, Collection<V>>> iterator() {
return Maps.asMapEntryIterator(multimap.keySet(), new Function<K, Collection<V>>() {
@Override
public Collection<V> apply(K key) {
return multimap.get(key);
}
});
}
@Override public boolean remove(Object o) {
if (!contains(o)) {
return false;
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
removeValuesForKey(entry.getKey());
return true;
}
}
@SuppressWarnings("unchecked")
@Override public Collection<V> get(Object key) {
return containsKey(key) ? multimap.get((K) key) : null;
}
@Override public Collection<V> remove(Object key) {
return containsKey(key) ? multimap.removeAll(key) : null;
}
@Override public Set<K> keySet() {
return multimap.keySet();
}
@Override public boolean isEmpty() {
return multimap.isEmpty();
}
@Override public boolean containsKey(Object key) {
return multimap.containsKey(key);
}
@Override public void clear() {
multimap.clear();
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals.
*
* @since 11.0
*/
public static <K, V> Multimap<K, V> filterKeys(
Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof SetMultimap) {
return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate);
} else if (unfiltered instanceof ListMultimap) {
return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate);
} else if (unfiltered instanceof FilteredKeyMultimap) {
FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered;
return new FilteredKeyMultimap<K, V>(prev.unfiltered,
Predicates.and(prev.keyPredicate, keyPredicate));
} else if (unfiltered instanceof FilteredMultimap) {
FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered;
return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
} else {
return new FilteredKeyMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals.
*
* @since 14.0
*/
public static <K, V> SetMultimap<K, V> filterKeys(
SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof FilteredKeySetMultimap) {
FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered;
return new FilteredKeySetMultimap<K, V>(prev.unfiltered(),
Predicates.and(prev.keyPredicate, keyPredicate));
} else if (unfiltered instanceof FilteredSetMultimap) {
FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered;
return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate));
} else {
return new FilteredKeySetMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose keys
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>,
* as documented at {@link Predicate#apply}. Do not provide a predicate such
* as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
* with equals.
*
* @since 14.0
*/
public static <K, V> ListMultimap<K, V> filterKeys(
ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
if (unfiltered instanceof FilteredKeyListMultimap) {
FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered;
return new FilteredKeyListMultimap<K, V>(prev.unfiltered(),
Predicates.and(prev.keyPredicate, keyPredicate));
} else {
return new FilteredKeyListMultimap<K, V>(unfiltered, keyPredicate);
}
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a value that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose value satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 11.0
*/
public static <K, V> Multimap<K, V> filterValues(
Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} whose values
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a value that doesn't satisfy the predicate, the
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose value satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}. Do not provide a
* predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is
* inconsistent with equals.
*
* @since 14.0
*/
public static <K, V> SetMultimap<K, V> filterValues(
SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key/value pair that doesn't satisfy the predicate,
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 11.0
*/
public static <K, V> Multimap<K, V> filterEntries(
Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
if (unfiltered instanceof SetMultimap) {
return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate);
}
return (unfiltered instanceof FilteredMultimap)
? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Returns a multimap containing the mappings in {@code unfiltered} that
* satisfy a predicate. The returned multimap is a live view of
* {@code unfiltered}; changes to one affect the other.
*
* <p>The resulting multimap's views have iterators that don't support
* {@code remove()}, but all other methods are supported by the multimap and
* its views. When adding a key/value pair that doesn't satisfy the predicate,
* multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()}
* methods throw an {@link IllegalArgumentException}.
*
* <p>When methods such as {@code removeAll()} and {@code clear()} are called on
* the filtered multimap or its views, only mappings whose keys satisfy the
* filter will be removed from the underlying multimap.
*
* <p>The returned multimap isn't threadsafe or serializable, even if
* {@code unfiltered} is.
*
* <p>Many of the filtered multimap's methods, such as {@code size()}, iterate
* across every key/value mapping in the underlying multimap and determine
* which satisfy the filter. When a live view is <i>not</i> needed, it may be
* faster to copy the filtered multimap and use the copy.
*
* <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with
* equals</i>, as documented at {@link Predicate#apply}.
*
* @since 14.0
*/
public static <K, V> SetMultimap<K, V> filterEntries(
SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
checkNotNull(entryPredicate);
return (unfiltered instanceof FilteredSetMultimap)
? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate)
: new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate);
}
/**
* Support removal operations when filtering a filtered multimap. Since a
* filtered multimap has iterators that don't support remove, passing one to
* the FilteredEntryMultimap constructor would lead to a multimap whose removal
* operations would fail. This method combines the predicates to avoid that
* problem.
*/
private static <K, V> Multimap<K, V> filterFiltered(FilteredMultimap<K, V> multimap,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(multimap.entryPredicate(), entryPredicate);
return new FilteredEntryMultimap<K, V>(multimap.unfiltered(), predicate);
}
/**
* Support removal operations when filtering a filtered multimap. Since a filtered multimap has
* iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would
* lead to a multimap whose removal operations would fail. This method combines the predicates to
* avoid that problem.
*/
private static <K, V> SetMultimap<K, V> filterFiltered(
FilteredSetMultimap<K, V> multimap,
Predicate<? super Entry<K, V>> entryPredicate) {
Predicate<Entry<K, V>> predicate
= Predicates.and(multimap.entryPredicate(), entryPredicate);
return new FilteredEntrySetMultimap<K, V>(multimap.unfiltered(), predicate);
}
static boolean equalsImpl(Multimap<?, ?> multimap, @Nullable Object object) {
if (object == multimap) {
return true;
}
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return multimap.asMap().equals(that.asMap());
}
return false;
}
// TODO(jlevy): Create methods that filter a SortedSetMultimap.
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of {@code Multimap} that does not allow duplicate key-value
* entries and that returns collections whose iterators follow the ordering in
* which the data was added to the multimap.
*
* <p>The collections returned by {@code keySet}, {@code keys}, and {@code
* asMap} iterate through the keys in the order they were first added to the
* multimap. Similarly, {@code get}, {@code removeAll}, and {@code
* replaceValues} return collections that iterate through the values in the
* order they were added. The collections generated by {@code entries} and
* {@code values} iterate across the key-value mappings in the order they were
* added to the multimap.
*
* <p>The iteration ordering of the collections generated by {@code keySet},
* {@code keys}, and {@code asMap} has a few subtleties. As long as the set of
* keys remains unchanged, adding or removing mappings does not affect the key
* iteration order. However, if you remove all values associated with a key and
* then add the key back to the multimap, that key will come last in the key
* iteration order.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new
* key-value pair equal to an existing key-value pair has no effect.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedSetMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> {
/**
* Creates a new, empty {@code LinkedHashMultimap} with the default initial
* capacities.
*/
public static <K, V> LinkedHashMultimap<K, V> create() {
return new LinkedHashMultimap<K, V>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY);
}
/**
* Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold
* the specified numbers of keys and values without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> LinkedHashMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new LinkedHashMultimap<K, V>(
Maps.capacity(expectedKeys),
Maps.capacity(expectedValuesPerKey));
}
/**
* Constructs a {@code LinkedHashMultimap} with the same mappings as the
* specified multimap. If a key-value mapping appears multiple times in the
* input multimap, it only appears once in the constructed multimap. The new
* multimap has the same {@link Multimap#entries()} iteration order as the
* input multimap, except for excluding duplicate mappings.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> LinkedHashMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY);
result.putAll(multimap);
return result;
}
private interface ValueSetLink<K, V> {
ValueSetLink<K, V> getPredecessorInValueSet();
ValueSetLink<K, V> getSuccessorInValueSet();
void setPredecessorInValueSet(ValueSetLink<K, V> entry);
void setSuccessorInValueSet(ValueSetLink<K, V> entry);
}
private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) {
pred.setSuccessorInValueSet(succ);
succ.setPredecessorInValueSet(pred);
}
private static <K, V> void succeedsInMultimap(
ValueEntry<K, V> pred, ValueEntry<K, V> succ) {
pred.setSuccessorInMultimap(succ);
succ.setPredecessorInMultimap(pred);
}
private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) {
succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet());
}
private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) {
succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap());
}
/**
* LinkedHashMultimap entries are in no less than three coexisting linked lists:
* a bucket in the hash table for a Set<V> associated with a key, the linked list
* of insertion-ordered entries in that Set<V>, and the linked list of entries
* in the LinkedHashMultimap as a whole.
*/
@VisibleForTesting
static final class ValueEntry<K, V> extends ImmutableEntry<K, V>
implements ValueSetLink<K, V> {
final int smearedValueHash;
@Nullable ValueEntry<K, V> nextInValueBucket;
ValueSetLink<K, V> predecessorInValueSet;
ValueSetLink<K, V> successorInValueSet;
ValueEntry<K, V> predecessorInMultimap;
ValueEntry<K, V> successorInMultimap;
ValueEntry(@Nullable K key, @Nullable V value, int smearedValueHash,
@Nullable ValueEntry<K, V> nextInValueBucket) {
super(key, value);
this.smearedValueHash = smearedValueHash;
this.nextInValueBucket = nextInValueBucket;
}
boolean matchesValue(@Nullable Object v, int smearedVHash) {
return smearedValueHash == smearedVHash && Objects.equal(getValue(), v);
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return predecessorInValueSet;
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return successorInValueSet;
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
predecessorInValueSet = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
successorInValueSet = entry;
}
public ValueEntry<K, V> getPredecessorInMultimap() {
return predecessorInMultimap;
}
public ValueEntry<K, V> getSuccessorInMultimap() {
return successorInMultimap;
}
public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) {
this.successorInMultimap = multimapSuccessor;
}
public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) {
this.predecessorInMultimap = multimapPredecessor;
}
}
private static final int DEFAULT_KEY_CAPACITY = 16;
private static final int DEFAULT_VALUE_SET_CAPACITY = 2;
@VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0;
@VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
private transient ValueEntry<K, V> multimapHeaderEntry;
private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) {
super(new LinkedHashMap<K, Collection<V>>(keyCapacity));
checkArgument(valueSetCapacity >= 0,
"expectedValuesPerKey must be >= 0 but was %s", valueSetCapacity);
this.valueSetCapacity = valueSetCapacity;
this.multimapHeaderEntry = new ValueEntry<K, V>(null, null, 0, null);
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code LinkedHashSet} for a collection of values for
* one key.
*
* @return a new {@code LinkedHashSet} containing a collection of values for
* one key
*/
@Override
Set<V> createCollection() {
return new LinkedHashSet<V>(valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>Creates a decorated insertion-ordered set that also keeps track of the
* order in which key-value pairs are added to the multimap.
*
* @param key key to associate with values in the collection
* @return a new decorated set containing a collection of values for one key
*/
@Override
Collection<V> createCollection(K key) {
return new ValueSet(key, valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>If {@code values} is not empty and the multimap already contains a
* mapping for {@code key}, the {@code keySet()} ordering is unchanged.
* However, the provided values always come last in the {@link #entries()} and
* {@link #values()} iteration orderings.
*/
@Override
public Set<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
return super.replaceValues(key, values);
}
/**
* Returns a set of all key-value pairs. Changes to the returned set will
* update the underlying multimap, and vice versa. The entries set does not
* support the {@code add} or {@code addAll} operations.
*
* <p>The iterator generated by the returned set traverses the entries in the
* order they were added to the multimap.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the
* multimap, taken at the time the entry is returned by a method call to the
* collection or its iterator.
*/
@Override public Set<Map.Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns a collection of all values in the multimap. Changes to the returned
* collection will update the underlying multimap, and vice versa.
*
* <p>The iterator generated by the returned collection traverses the values
* in the order they were added to the multimap.
*/
@Override public Collection<V> values() {
return super.values();
}
@VisibleForTesting
final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> {
/*
* We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory
* consumption.
*/
private final K key;
@VisibleForTesting ValueEntry<K, V>[] hashTable;
private int size = 0;
private int modCount = 0;
// We use the set object itself as the end of the linked list, avoiding an unnecessary
// entry object per key.
private ValueSetLink<K, V> firstEntry;
private ValueSetLink<K, V> lastEntry;
ValueSet(K key, int expectedValues) {
this.key = key;
this.firstEntry = this;
this.lastEntry = this;
// Round expected values up to a power of 2 to get the table size.
int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR);
@SuppressWarnings("unchecked")
ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize];
this.hashTable = hashTable;
}
private int mask() {
return hashTable.length - 1;
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return lastEntry;
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return firstEntry;
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
lastEntry = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
firstEntry = entry;
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
ValueSetLink<K, V> nextEntry = firstEntry;
ValueEntry<K, V> toRemove;
int expectedModCount = modCount;
private void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForComodification();
return nextEntry != ValueSet.this;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry;
V result = entry.getValue();
toRemove = entry;
nextEntry = entry.getSuccessorInValueSet();
return result;
}
@Override
public void remove() {
checkForComodification();
Iterators.checkRemove(toRemove != null);
ValueSet.this.remove(toRemove.getValue());
expectedModCount = modCount;
toRemove = null;
}
};
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(@Nullable Object o) {
int smearedHash = Hashing.smearedHash(o);
for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()]; entry != null;
entry = entry.nextInValueBucket) {
if (entry.matchesValue(o, smearedHash)) {
return true;
}
}
return false;
}
@Override
public boolean add(@Nullable V value) {
int smearedHash = Hashing.smearedHash(value);
int bucket = smearedHash & mask();
ValueEntry<K, V> rowHead = hashTable[bucket];
for (ValueEntry<K, V> entry = rowHead; entry != null;
entry = entry.nextInValueBucket) {
if (entry.matchesValue(value, smearedHash)) {
return false;
}
}
ValueEntry<K, V> newEntry = new ValueEntry<K, V>(key, value, smearedHash, rowHead);
succeedsInValueSet(lastEntry, newEntry);
succeedsInValueSet(newEntry, this);
succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry);
succeedsInMultimap(newEntry, multimapHeaderEntry);
hashTable[bucket] = newEntry;
size++;
modCount++;
rehashIfNecessary();
return true;
}
private void rehashIfNecessary() {
if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) {
@SuppressWarnings("unchecked")
ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2];
this.hashTable = hashTable;
int mask = hashTable.length - 1;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this; entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
int bucket = valueEntry.smearedValueHash & mask;
valueEntry.nextInValueBucket = hashTable[bucket];
hashTable[bucket] = valueEntry;
}
}
}
@Override
public boolean remove(@Nullable Object o) {
int smearedHash = Hashing.smearedHash(o);
int bucket = smearedHash & mask();
ValueEntry<K, V> prev = null;
for (ValueEntry<K, V> entry = hashTable[bucket]; entry != null;
prev = entry, entry = entry.nextInValueBucket) {
if (entry.matchesValue(o, smearedHash)) {
if (prev == null) {
// first entry in the bucket
hashTable[bucket] = entry.nextInValueBucket;
} else {
prev.nextInValueBucket = entry.nextInValueBucket;
}
deleteFromValueSet(entry);
deleteFromMultimap(entry);
size--;
modCount++;
return true;
}
}
return false;
}
@Override
public void clear() {
Arrays.fill(hashTable, null);
size = 0;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this; entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
deleteFromMultimap(valueEntry);
}
succeedsInValueSet(this, this);
modCount++;
}
}
@Override
Iterator<Map.Entry<K, V>> entryIterator() {
return new Iterator<Map.Entry<K, V>>() {
ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap;
ValueEntry<K, V> toRemove;
@Override
public boolean hasNext() {
return nextEntry != multimapHeaderEntry;
}
@Override
public Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> result = nextEntry;
toRemove = result;
nextEntry = nextEntry.successorInMultimap;
return result;
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue());
toRemove = null;
}
};
}
@Override
Iterator<V> valueIterator() {
return Maps.valueIterator(entryIterator());
}
@Override
public void clear() {
super.clear();
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* A sorted set of contiguous values in a given {@link DiscreteDomain}.
*
* <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
* {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomain.integers()}). Certain
* operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode}
* or {@link Collections#frequency}) can cause major performance problems.
*
* @author Gregory Kick
* @since 10.0
*/
@Beta
@GwtCompatible(emulated = true)
@SuppressWarnings("rawtypes") // allow ungenerified Comparable types
public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
/**
* Returns a {@code ContiguousSet} containing the same values in the given domain
* {@linkplain Range#contains contained} by the range.
*
* @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
* neither has an upper bound
*
* @since 13.0
*/
public static <C extends Comparable> ContiguousSet<C> create(
Range<C> range, DiscreteDomain<C> domain) {
checkNotNull(range);
checkNotNull(domain);
Range<C> effectiveRange = range;
try {
if (!range.hasLowerBound()) {
effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
}
if (!range.hasUpperBound()) {
effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
}
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(e);
}
// Per class spec, we are allowed to throw CCE if necessary
boolean empty = effectiveRange.isEmpty()
|| Range.compareOrThrow(
range.lowerBound.leastValueAbove(domain),
range.upperBound.greatestValueBelow(domain)) > 0;
return empty
? new EmptyContiguousSet<C>(domain)
: new RegularContiguousSet<C>(effectiveRange, domain);
}
final DiscreteDomain<C> domain;
ContiguousSet(DiscreteDomain<C> domain) {
super(Ordering.natural());
this.domain = domain;
}
@Override public ContiguousSet<C> headSet(C toElement) {
return headSetImpl(checkNotNull(toElement), false);
}
@Override public ContiguousSet<C> subSet(C fromElement, C toElement) {
checkNotNull(fromElement);
checkNotNull(toElement);
checkArgument(comparator().compare(fromElement, toElement) <= 0);
return subSetImpl(fromElement, true, toElement, false);
}
@Override public ContiguousSet<C> tailSet(C fromElement) {
return tailSetImpl(checkNotNull(fromElement), true);
}
/*
* These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
*/
/*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
/*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive,
C toElement, boolean toInclusive);
/*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
/**
* Returns the set of values that are contained in both this set and the other.
*
* <p>This method should always be used instead of
* {@link Sets#intersection} for {@link ContiguousSet} instances.
*/
public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
/**
* Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
* contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range();
/**
* Returns the minimal range with the given boundary types for which all values in this set are
* {@linkplain Range#contains(Comparable) contained} within the range.
*
* <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
* is requested for a domain minimum or maximum. For example, if {@code set} was created from the
* range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
* {@code [1..∞)}.
*
* @throws NoSuchElementException if this set is empty
*/
public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
/** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
@Override public String toString() {
return range().toString();
}
/**
* Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
* method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
* ContiguousSet}.
*
* @throws UnsupportedOperationException always
* @deprecated Use {@link #create}.
*/
@Deprecated public static <E> ImmutableSortedSet.Builder<E> builder() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.SortedSet;
/**
* GWT emulation of {@link RegularImmutableSortedSet}.
*
* @author Hayward Chan
*/
final class RegularImmutableSortedSet<E> extends ImmutableSortedSet<E> {
/** true if this set is a subset of another immutable sorted set. */
final boolean isSubset;
RegularImmutableSortedSet(SortedSet<E> delegate, boolean isSubset) {
super(delegate);
this.isSubset = isSubset;
}
@Override ImmutableList<E> createAsList() {
return new ImmutableSortedAsList<E>(this, ImmutableList.<E>asImmutableList(toArray()));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Ints;
import java.io.Serializable;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Basic implementation of {@code Multiset<E>} backed by an instance of {@code
* Map<E, Count>}.
*
* <p>For serialization to work, the subclass must specify explicit {@code
* readObject} and {@code writeObject} methods.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E>
implements Serializable {
private transient Map<E, Count> backingMap;
/*
* Cache the size for efficiency. Using a long lets us avoid the need for
* overflow checking and ensures that size() will function correctly even if
* the multiset had once been larger than Integer.MAX_VALUE.
*/
private transient long size;
/** Standard constructor. */
protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
this.backingMap = checkNotNull(backingMap);
this.size = super.size();
}
/** Used during deserialization only. The backing map must be empty. */
void setBackingMap(Map<E, Count> backingMap) {
this.backingMap = backingMap;
}
// Required Implementations
/**
* {@inheritDoc}
*
* <p>Invoking {@link Multiset.Entry#getCount} on an entry in the returned
* set always returns the current count of that element in the multiset, as
* opposed to the count at the time the entry was retrieved.
*/
@Override
public Set<Multiset.Entry<E>> entrySet() {
return super.entrySet();
}
@Override
Iterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Count>> backingEntries =
backingMap.entrySet().iterator();
return new Iterator<Multiset.Entry<E>>() {
Map.Entry<E, Count> toRemove;
@Override
public boolean hasNext() {
return backingEntries.hasNext();
}
@Override
public Multiset.Entry<E> next() {
final Map.Entry<E, Count> mapEntry = backingEntries.next();
toRemove = mapEntry;
return new Multisets.AbstractEntry<E>() {
@Override
public E getElement() {
return mapEntry.getKey();
}
@Override
public int getCount() {
Count count = mapEntry.getValue();
if (count == null || count.get() == 0) {
Count frequency = backingMap.get(getElement());
if (frequency != null) {
return frequency.get();
}
}
return (count == null) ? 0 : count.get();
}
};
}
@Override
public void remove() {
Iterators.checkRemove(toRemove != null);
size -= toRemove.getValue().getAndSet(0);
backingEntries.remove();
toRemove = null;
}
};
}
@Override
public void clear() {
for (Count frequency : backingMap.values()) {
frequency.set(0);
}
backingMap.clear();
size = 0L;
}
@Override
int distinctElements() {
return backingMap.size();
}
// Optimizations - Query Operations
@Override public int size() {
return Ints.saturatedCast(size);
}
@Override public Iterator<E> iterator() {
return new MapBasedMultisetIterator();
}
/*
* Not subclassing AbstractMultiset$MultisetIterator because next() needs to
* retrieve the Map.Entry<E, Count> entry, which can then be used for
* a more efficient remove() call.
*/
private class MapBasedMultisetIterator implements Iterator<E> {
final Iterator<Map.Entry<E, Count>> entryIterator;
Map.Entry<E, Count> currentEntry;
int occurrencesLeft;
boolean canRemove;
MapBasedMultisetIterator() {
this.entryIterator = backingMap.entrySet().iterator();
}
@Override
public boolean hasNext() {
return occurrencesLeft > 0 || entryIterator.hasNext();
}
@Override
public E next() {
if (occurrencesLeft == 0) {
currentEntry = entryIterator.next();
occurrencesLeft = currentEntry.getValue().get();
}
occurrencesLeft--;
canRemove = true;
return currentEntry.getKey();
}
@Override
public void remove() {
checkState(canRemove,
"no calls to next() since the last call to remove()");
int frequency = currentEntry.getValue().get();
if (frequency <= 0) {
throw new ConcurrentModificationException();
}
if (currentEntry.getValue().addAndGet(-1) == 0) {
entryIterator.remove();
}
size--;
canRemove = false;
}
}
@Override public int count(@Nullable Object element) {
Count frequency = Maps.safeGet(backingMap, element);
return (frequency == null) ? 0 : frequency.get();
}
// Optional Operations - Modification Operations
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the call would result in more than
* {@link Integer#MAX_VALUE} occurrences of {@code element} in this
* multiset.
*/
@Override public int add(@Nullable E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
int oldCount;
if (frequency == null) {
oldCount = 0;
backingMap.put(element, new Count(occurrences));
} else {
oldCount = frequency.get();
long newCount = (long) oldCount + (long) occurrences;
checkArgument(newCount <= Integer.MAX_VALUE,
"too many occurrences: %s", newCount);
frequency.getAndAdd(occurrences);
}
size += occurrences;
return oldCount;
}
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(
occurrences > 0, "occurrences cannot be negative: %s", occurrences);
Count frequency = backingMap.get(element);
if (frequency == null) {
return 0;
}
int oldCount = frequency.get();
int numberRemoved;
if (oldCount > occurrences) {
numberRemoved = occurrences;
} else {
numberRemoved = oldCount;
backingMap.remove(element);
}
frequency.addAndGet(-numberRemoved);
size -= numberRemoved;
return oldCount;
}
// Roughly a 33% performance improvement over AbstractMultiset.setCount().
@Override public int setCount(@Nullable E element, int count) {
checkNonnegative(count, "count");
Count existingCounter;
int oldCount;
if (count == 0) {
existingCounter = backingMap.remove(element);
oldCount = getAndSet(existingCounter, count);
} else {
existingCounter = backingMap.get(element);
oldCount = getAndSet(existingCounter, count);
if (existingCounter == null) {
backingMap.put(element, new Count(count));
}
}
size += (count - oldCount);
return oldCount;
}
private static int getAndSet(Count i, int count) {
if (i == null) {
return 0;
}
return i.getAndSet(count);
}
// Don't allow default serialization.
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* A class exactly like {@link MapMaker}, except restricted in the types of maps it can build.
* For the most part, you should probably just ignore the existence of this class.
*
* @param <K0> the base type for all key types of maps built by this map maker
* @param <V0> the base type for all value types of maps built by this map maker
* @author Kevin Bourrillion
* @since 7.0
* @deprecated This class existed only to support the generic paramterization necessary for the
* caching functionality in {@code MapMaker}. That functionality has been moved to {@link
* com.google.common.cache.CacheBuilder}, which is a properly generified class and thus needs no
* "Generic" equivalent; simple use {@code CacheBuilder} naturally. For general migration
* instructions, see the <a
* href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker Migration
* Guide</a>. This class is scheduled for removal in Guava 16.0.
*/
@Beta
@Deprecated
@GwtCompatible(emulated = true)
public abstract class GenericMapMaker<K0, V0> {
// Set by MapMaker, but sits in this class to preserve the type relationship
// No subclasses but our own
GenericMapMaker() {}
/**
* See {@link MapMaker#initialCapacity}.
*/
public abstract GenericMapMaker<K0, V0> initialCapacity(int initialCapacity);
/**
* See {@link MapMaker#maximumSize}.
*/
abstract GenericMapMaker<K0, V0> maximumSize(int maximumSize);
/**
* See {@link MapMaker#concurrencyLevel}.
*/
public abstract GenericMapMaker<K0, V0> concurrencyLevel(int concurrencyLevel);
/**
* See {@link MapMaker#expireAfterWrite}.
*/
abstract GenericMapMaker<K0, V0> expireAfterWrite(long duration, TimeUnit unit);
/*
* Note that MapMaker's removalListener() is not here, because once you're interacting with a
* GenericMapMaker you've already called that, and shouldn't be calling it again.
*/
/**
* See {@link MapMaker#makeMap}.
*/
public abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeMap();
/**
* See {@link MapMaker#makeComputingMap}.
*/
@Deprecated
abstract <K extends K0, V extends V0> ConcurrentMap<K, V> makeComputingMap(
Function<? super K, ? extends V> computingFunction);
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
/**
* Implementation of {@code Multimap} that uses an {@code ArrayList} to store
* the values for a given key. A {@link HashMap} associates each key with an
* {@link ArrayList} of values.
*
* <p>When iterating through the collections supplied by this class, the
* ordering of values for a given key agrees with the order in which the values
* were added.
*
* <p>This multimap allows duplicate key-value pairs. After adding a new
* key-value pair equal to an existing key-value pair, the {@code
* ArrayListMultimap} will contain entries for both the new value and the old
* value.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link
* #replaceValues} all implement {@link java.util.RandomAccess}.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedListMultimap}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
* {@code Multimap}</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> {
// Default from ArrayList
private static final int DEFAULT_VALUES_PER_KEY = 3;
@VisibleForTesting transient int expectedValuesPerKey;
/**
* Creates a new, empty {@code ArrayListMultimap} with the default initial
* capacities.
*/
public static <K, V> ArrayListMultimap<K, V> create() {
return new ArrayListMultimap<K, V>();
}
/**
* Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
* the specified numbers of keys and values without resizing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> ArrayListMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
}
/**
* Constructs an {@code ArrayListMultimap} with the same mappings as the
* specified multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> ArrayListMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new ArrayListMultimap<K, V>(multimap);
}
private ArrayListMultimap() {
super(new HashMap<K, Collection<V>>());
expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
}
private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
}
private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
this(multimap.keySet().size(),
(multimap instanceof ArrayListMultimap) ?
((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
DEFAULT_VALUES_PER_KEY);
putAll(multimap);
}
/**
* Creates a new, empty {@code ArrayList} to hold the collection of values for
* an arbitrary key.
*/
@Override List<V> createCollection() {
return new ArrayList<V>(expectedValuesPerKey);
}
/**
* Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
*/
public void trimToSize() {
for (Collection<V> collection : backingMap().values()) {
ArrayList<V> arrayList = (ArrayList<V>) collection;
arrayList.trimToSize();
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
/**
* GWT emulation of {@link SingletonImmutableSet}.
*
* @author Hayward Chan
*/
final class SingletonImmutableSet<E> extends ImmutableSet<E> {
// This reference is used both by the custom field serializer, and by the
// GWT compiler to infer the elements of the lists that needs to be
// serialized.
//
// Although this reference is non-final, it doesn't change after set creation.
E element;
SingletonImmutableSet(E element) {
this.element = checkNotNull(element);
}
@Override
public int size() {
return 1;
}
@Override
public UnmodifiableIterator<E> iterator() {
return Iterators.singletonIterator(element);
}
@Override
public boolean contains(Object object) {
return element.equals(object);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An empty contiguous set.
*
* @author Gregory Kick
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("unchecked") // allow ungenerified Comparable types
final class EmptyContiguousSet<C extends Comparable> extends ContiguousSet<C> {
EmptyContiguousSet(DiscreteDomain<C> domain) {
super(domain);
}
@Override public C first() {
throw new NoSuchElementException();
}
@Override public C last() {
throw new NoSuchElementException();
}
@Override public int size() {
return 0;
}
@Override public ContiguousSet<C> intersection(ContiguousSet<C> other) {
return this;
}
@Override public Range<C> range() {
throw new NoSuchElementException();
}
@Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) {
throw new NoSuchElementException();
}
@Override ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) {
return this;
}
@Override ContiguousSet<C> subSetImpl(
C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
return this;
}
@Override ContiguousSet<C> tailSetImpl(C fromElement, boolean fromInclusive) {
return this;
}
@Override public UnmodifiableIterator<C> iterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override public boolean isEmpty() {
return true;
}
@Override public ImmutableList<C> asList() {
return ImmutableList.of();
}
@Override public String toString() {
return "[]";
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public int hashCode() {
return 0;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* GWT emulation of {@code HashBiMap} that just delegates to two HashMaps.
*
* @author Mike Bostock
*/
public final class HashBiMap<K, V> extends AbstractBiMap<K, V> {
/**
* Returns a new, empty {@code HashBiMap} with the default initial capacity
* (16).
*/
public static <K, V> HashBiMap<K, V> create() {
return new HashBiMap<K, V>();
}
/**
* Constructs a new, empty bimap with the specified expected size.
*
* @param expectedSize the expected number of entries
* @throws IllegalArgumentException if the specified expected size is
* negative
*/
public static <K, V> HashBiMap<K, V> create(int expectedSize) {
return new HashBiMap<K, V>(expectedSize);
}
/**
* Constructs a new bimap containing initial values from {@code map}. The
* bimap is created with an initial capacity sufficient to hold the mappings
* in the specified map.
*/
public static <K, V> HashBiMap<K, V> create(
Map<? extends K, ? extends V> map) {
HashBiMap<K, V> bimap = create(map.size());
bimap.putAll(map);
return bimap;
}
private HashBiMap() {
super(new HashMap<K, V>(), new HashMap<V, K>());
}
private HashBiMap(int expectedSize) {
super(
Maps.<K, V>newHashMapWithExpectedSize(expectedSize),
Maps.<V, K>newHashMapWithExpectedSize(expectedSize));
}
// Override these two methods to show that keys and values may be null
@Override public V put(@Nullable K key, @Nullable V value) {
return super.put(key, value);
}
@Override public V forcePut(@Nullable K key, @Nullable V value) {
return super.forcePut(key, value);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Comparator;
/**
* GWT emulation of {@link EmptyImmutableSortedSet}.
*
* @author Hayward Chan
*/
class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> {
EmptyImmutableSortedSet(Comparator<? super E> comparator) {
super(Sets.newTreeSet(comparator));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
/**
* Implementation of {@link Multimap} using hash tables.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new
* key-value pair equal to an existing key-value pair has no effect.
*
* <p>Keys and values may be null. All optional multimap methods are supported,
* and all returned views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the
* multimap. Concurrent read operations will work correctly. To allow concurrent
* update operations, wrap your multimap with a call to {@link
* Multimaps#synchronizedSetMultimap}.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public final class HashMultimap<K, V> extends AbstractSetMultimap<K, V> {
private static final int DEFAULT_VALUES_PER_KEY = 2;
@VisibleForTesting
transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
/**
* Creates a new, empty {@code HashMultimap} with the default initial
* capacities.
*/
public static <K, V> HashMultimap<K, V> create() {
return new HashMultimap<K, V>();
}
/**
* Constructs an empty {@code HashMultimap} with enough capacity to hold the
* specified numbers of keys and values without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code
* expectedValuesPerKey} is negative
*/
public static <K, V> HashMultimap<K, V> create(
int expectedKeys, int expectedValuesPerKey) {
return new HashMultimap<K, V>(expectedKeys, expectedValuesPerKey);
}
/**
* Constructs a {@code HashMultimap} with the same mappings as the specified
* multimap. If a key-value mapping appears multiple times in the input
* multimap, it only appears once in the constructed multimap.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K, V> HashMultimap<K, V> create(
Multimap<? extends K, ? extends V> multimap) {
return new HashMultimap<K, V>(multimap);
}
private HashMultimap() {
super(new HashMap<K, Collection<V>>());
}
private HashMultimap(int expectedKeys, int expectedValuesPerKey) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
Preconditions.checkArgument(expectedValuesPerKey >= 0);
this.expectedValuesPerKey = expectedValuesPerKey;
}
private HashMultimap(Multimap<? extends K, ? extends V> multimap) {
super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(
multimap.keySet().size()));
putAll(multimap);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code HashSet} for a collection of values for one key.
*
* @return a new {@code HashSet} containing a collection of values for one key
*/
@Override Set<V> createCollection() {
return Sets.<V>newHashSetWithExpectedSize(expectedValuesPerKey);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable {@link Multimap}. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>In addition to methods defined by {@link Multimap}, an {@link #inverse}
* method is also supported.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public abstract class ImmutableMultimap<K, V> extends AbstractMultimap<K, V>
implements Serializable {
/** Returns an empty multimap. */
public static <K, V> ImmutableMultimap<K, V> of() {
return ImmutableListMultimap.of();
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
return ImmutableListMultimap.of(k1, v1);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
return ImmutableListMultimap.of(k1, v1, k2, v2);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableMultimap.Builder} that maintains key and
* value orderings, allows duplicate values, and performs better than
* {@link LinkedListMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Lists.newArrayList();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable multimap instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* <p>Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<K, V> {
Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>();
Comparator<? super K> keyComparator;
Comparator<? super V> valueComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultimap#builder}.
*/
public Builder() {}
/**
* Adds a key-value mapping to the built multimap.
*/
public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap.
*
* @since 11.0
*/
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
/**
* Stores a collection of values with the same key in the built multimap.
*
* @throws NullPointerException if {@code key}, {@code values}, or any
* element in {@code values} is null. The builder is left in an invalid
* state.
*/
public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> valueList = builderMultimap.get(checkNotNull(key));
for (V value : values) {
valueList.add(checkNotNull(value));
}
return this;
}
/**
* Stores an array of values with the same key in the built multimap.
*
* @throws NullPointerException if the key or any value is null. The builder
* is left in an invalid state.
*/
public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
/**
* Stores another multimap's entries in the built multimap. The generated
* multimap's key and value orderings correspond to the iteration ordering
* of the {@code multimap.asMap()} view, with new keys and values following
* any existing keys and values.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null. The builder is left in an invalid state.
*/
public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Specifies the ordering of the generated multimap's keys.
*
* @since 8.0
*/
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
this.keyComparator = checkNotNull(keyComparator);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* @since 8.0
*/
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
this.valueComparator = checkNotNull(valueComparator);
return this;
}
/**
* Returns a newly-created immutable multimap.
*/
public ImmutableMultimap<K, V> build() {
if (valueComparator != null) {
for (Collection<V> values : builderMultimap.asMap().values()) {
List<V> list = (List <V>) values;
Collections.sort(list, valueComparator);
}
}
if (keyComparator != null) {
Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>();
List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList(
builderMultimap.asMap().entrySet());
Collections.sort(
entries,
Ordering.from(keyComparator).<K>onKeys());
for (Map.Entry<K, Collection<V>> entry : entries) {
sortedCopy.putAll(entry.getKey(), entry.getValue());
}
builderMultimap = sortedCopy;
}
return copyOf(builderMultimap);
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code
* multimap}. The generated multimap's key and value orderings correspond to
* the iteration ordering of the {@code multimap.asMap()} view.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap instanceof ImmutableMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableMultimap<K, V> kvMultimap
= (ImmutableMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
return ImmutableListMultimap.copyOf(multimap);
}
final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
final transient int size;
// These constants allow the deserialization code to set final fields. This
// holder class makes sure they are not initialized unless an instance is
// deserialized.
ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map,
int size) {
this.map = map;
this.size = size;
}
// mutators (not supported)
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public ImmutableCollection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public ImmutableCollection<V> replaceValues(K key,
Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public void clear() {
throw new UnsupportedOperationException();
}
/**
* Returns an immutable collection of the values for the given key. If no
* mappings in the multimap have the provided key, an empty immutable
* collection is returned. The values are in the same order as the parameters
* used to build this multimap.
*/
@Override
public abstract ImmutableCollection<V> get(K key);
/**
* Returns an immutable multimap which is the inverse of this one. For every
* key-value mapping in the original, the result will have a mapping with
* key and value reversed.
*
* @since 11.0
*/
public abstract ImmutableMultimap<V, K> inverse();
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
/**
* Returns {@code true} if this immutable multimap's implementation contains references to
* user-created objects that aren't accessible via this multimap's methods. This is generally
* used to determine whether {@code copyOf} implementations should make an explicit copy to avoid
* memory leaks.
*/
boolean isPartialView() {
return map.isPartialView();
}
// accessors
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
return value != null && super.containsValue(value);
}
@Override
public int size() {
return size;
}
// views
/**
* Returns an immutable set of the distinct keys in this multimap. These keys
* are ordered according to when they first appeared during the construction
* of this multimap.
*/
@Override
public ImmutableSet<K> keySet() {
return map.keySet();
}
/**
* Returns an immutable map that associates each key with its corresponding
* values in the multimap.
*/
@Override
@SuppressWarnings("unchecked") // a widening cast
public ImmutableMap<K, Collection<V>> asMap() {
return (ImmutableMap) map;
}
@Override
Map<K, Collection<V>> createAsMap() {
throw new AssertionError("should never be called");
}
/**
* Returns an immutable collection of all key-value pairs in the multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<Entry<K, V>> entries() {
return (ImmutableCollection<Entry<K, V>>) super.entries();
}
@Override
ImmutableCollection<Entry<K, V>> createEntries() {
return new EntryCollection<K, V>(this);
}
private static class EntryCollection<K, V>
extends ImmutableCollection<Entry<K, V>> {
final ImmutableMultimap<K, V> multimap;
EntryCollection(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override public UnmodifiableIterator<Entry<K, V>> iterator() {
return multimap.entryIterator();
}
@Override boolean isPartialView() {
return multimap.isPartialView();
}
@Override
public int size() {
return multimap.size();
}
@Override public boolean contains(Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
private static final long serialVersionUID = 0;
}
private abstract class Itr<T> extends UnmodifiableIterator<T> {
final Iterator<Entry<K, Collection<V>>> mapIterator = asMap().entrySet().iterator();
K key = null;
Iterator<V> valueIterator = Iterators.emptyIterator();
abstract T output(K key, V value);
@Override
public boolean hasNext() {
return mapIterator.hasNext() || valueIterator.hasNext();
}
@Override
public T next() {
if (!valueIterator.hasNext()) {
Entry<K, Collection<V>> mapEntry = mapIterator.next();
key = mapEntry.getKey();
valueIterator = mapEntry.getValue().iterator();
}
return output(key, valueIterator.next());
}
}
@Override
UnmodifiableIterator<Entry<K, V>> entryIterator() {
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> output(K key, V value) {
return Maps.immutableEntry(key, value);
}
};
}
/**
* Returns a collection, which may contain duplicates, of all keys. The number
* of times a key appears in the returned multiset equals the number of
* mappings the key has in the multimap. Duplicate keys appear consecutively
* in the multiset's iteration order.
*/
@Override
public ImmutableMultiset<K> keys() {
return (ImmutableMultiset<K>) super.keys();
}
@Override
ImmutableMultiset<K> createKeys() {
return new Keys();
}
@SuppressWarnings("serial") // Uses writeReplace, not default serialization
class Keys extends ImmutableMultiset<K> {
@Override
public boolean contains(@Nullable Object object) {
return containsKey(object);
}
@Override
public int count(@Nullable Object element) {
Collection<V> values = map.get(element);
return (values == null) ? 0 : values.size();
}
@Override
public Set<K> elementSet() {
return keySet();
}
@Override
public int size() {
return ImmutableMultimap.this.size();
}
@Override
Multiset.Entry<K> getEntry(int index) {
Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index);
return Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
}
@Override
boolean isPartialView() {
return true;
}
}
/**
* Returns an immutable collection of the values in this multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<V> values() {
return (ImmutableCollection<V>) super.values();
}
@Override
ImmutableCollection<V> createValues() {
return new Values<K, V>(this);
}
@Override
UnmodifiableIterator<V> valueIterator() {
return new Itr<V>() {
@Override
V output(K key, V value) {
return value;
}
};
}
private static final class Values<K, V> extends ImmutableCollection<V> {
private transient final ImmutableMultimap<K, V> multimap;
Values(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override
public boolean contains(@Nullable Object object) {
return multimap.containsValue(object);
}
@Override public UnmodifiableIterator<V> iterator() {
return multimap.valueIterator();
}
@Override
public int size() {
return multimap.size();
}
@Override boolean isPartialView() {
return true;
}
private static final long serialVersionUID = 0;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newTreeMap;
import static java.util.Collections.unmodifiableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
/**
* GWT emulated version of {@link ImmutableSortedMap}. It's a thin wrapper
* around a {@link java.util.TreeMap}.
*
* @author Hayward Chan
*/
public abstract class ImmutableSortedMap<K, V>
extends ForwardingImmutableMap<K, V> implements SortedMap<K, V> {
@SuppressWarnings("unchecked")
static final Comparator NATURAL_ORDER = Ordering.natural();
// This reference is only used by GWT compiler to infer the keys and values
// of the map that needs to be serialized.
private Comparator<? super K> unusedComparatorForSerialization;
private K unusedKeyForSerialization;
private V unusedValueForSerialization;
private final transient SortedMap<K, V> sortedDelegate;
// The comparator used by this map. It's the same as that of sortedDelegate,
// except that when sortedDelegate's comparator is null, it points to a
// non-null instance of Ordering.natural().
// (cpovirk: Is sortedDelegate's comparator really ever null?)
// The comparator will likely also differ because of our nullAccepting hack.
// See the bottom of the file for more information about it.
private final transient Comparator<? super K> comparator;
ImmutableSortedMap(SortedMap<K, V> delegate, Comparator<? super K> comparator) {
super(delegate);
this.comparator = comparator;
this.sortedDelegate = delegate;
}
private static <K, V> ImmutableSortedMap<K, V> create(
Comparator<? super K> comparator,
Entry<? extends K, ? extends V>... entries) {
checkNotNull(comparator);
SortedMap<K, V> delegate = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : entries) {
delegate.put(entry.getKey(), entry.getValue());
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
// Casting to any type is safe because the set will never hold any elements.
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSortedMap<K, V> of() {
return EmptyImmutableSortedMap.forComparator(NATURAL_ORDER);
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1) {
return create(Ordering.natural(), entryOf(k1, v1));
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).build();
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).build();
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).build();
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).put(k5, v5).build();
}
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
copyOf(Map<? extends K, ? extends V> map) {
return copyOfInternal(map, Ordering.natural());
}
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
return copyOfInternal(map, checkNotNull(comparator));
}
public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(
SortedMap<K, ? extends V> map) {
// If map has a null comparator, the keys should have a natural ordering,
// even though K doesn't explicitly implement Comparable.
@SuppressWarnings("unchecked")
Comparator<? super K> comparator =
(map.comparator() == null) ? NATURAL_ORDER : map.comparator();
return copyOfInternal(map, comparator);
}
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
if (map instanceof ImmutableSortedMap) {
// TODO: Prove that this cast is safe, even though
// Collections.unmodifiableSortedMap requires the same key type.
@SuppressWarnings("unchecked")
ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
Comparator<?> comparator2 = kvMap.comparator();
boolean sameComparator = (comparator2 == null)
? comparator == NATURAL_ORDER
: comparator.equals(comparator2);
if (sameComparator) {
return kvMap;
}
}
SortedMap<K, V> delegate = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
putEntryWithChecks(delegate, entry);
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
private static <K, V> void putEntryWithChecks(
SortedMap<K, V> map, Entry<? extends K, ? extends V> entry) {
K key = checkNotNull(entry.getKey());
V value = checkNotNull(entry.getValue());
if (map.containsKey(key)) {
// When a collision happens, the colliding entry is the first entry
// of the tail map.
Entry<K, V> previousEntry
= map.tailMap(key).entrySet().iterator().next();
throw new IllegalArgumentException(
"Duplicate keys in mappings " + previousEntry.getKey() +
"=" + previousEntry.getValue() + " and " + key +
"=" + value);
}
map.put(key, value);
}
public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() {
return new Builder<K, V>(Ordering.natural());
}
public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
return new Builder<K, V>(comparator);
}
public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
return new Builder<K, V>(Ordering.natural().reverse());
}
public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
private final Comparator<? super K> comparator;
public Builder(Comparator<? super K> comparator) {
this.comparator = checkNotNull(comparator);
}
@Override public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
@Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
@Override public ImmutableSortedMap<K, V> build() {
SortedMap<K, V> delegate = newModifiableDelegate(comparator);
for (Entry<? extends K, ? extends V> entry : entries) {
putEntryWithChecks(delegate, entry);
}
return newView(unmodifiableSortedMap(delegate), comparator);
}
}
private transient ImmutableSortedSet<K> keySet;
@Override public ImmutableSortedSet<K> keySet() {
ImmutableSortedSet<K> ks = keySet;
return (ks == null) ? (keySet = createKeySet()) : ks;
}
@Override ImmutableSortedSet<K> createKeySet() {
// the keySet() of the delegate is only a Set and TreeMap.navigatableKeySet
// is not available in GWT yet. To keep the code simple and code size more,
// we make a copy here, instead of creating a view of it.
//
// TODO: revisit if it's unbearably slow or when GWT supports
// TreeMap.navigatbleKeySet().
return ImmutableSortedSet.copyOf(comparator, sortedDelegate.keySet());
}
public Comparator<? super K> comparator() {
return comparator;
}
public K firstKey() {
return sortedDelegate.firstKey();
}
public K lastKey() {
return sortedDelegate.lastKey();
}
K higher(K k) {
Iterator<K> iterator = keySet().tailSet(k).iterator();
while (iterator.hasNext()) {
K tmp = iterator.next();
if (comparator().compare(k, tmp) < 0) {
return tmp;
}
}
return null;
}
public ImmutableSortedMap<K, V> headMap(K toKey) {
checkNotNull(toKey);
return newView(sortedDelegate.headMap(toKey));
}
ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
checkNotNull(toKey);
if (inclusive) {
K tmp = higher(toKey);
if (tmp == null) {
return this;
}
toKey = tmp;
}
return headMap(toKey);
}
public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
checkNotNull(fromKey);
checkNotNull(toKey);
checkArgument(comparator.compare(fromKey, toKey) <= 0);
return newView(sortedDelegate.subMap(fromKey, toKey));
}
ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
checkNotNull(fromKey);
checkNotNull(toKey);
checkArgument(comparator.compare(fromKey, toKey) <= 0);
return tailMap(fromKey, fromInclusive).headMap(toKey, toInclusive);
}
public ImmutableSortedMap<K, V> tailMap(K fromKey) {
checkNotNull(fromKey);
return newView(sortedDelegate.tailMap(fromKey));
}
public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
checkNotNull(fromKey);
if (!inclusive) {
fromKey = higher(fromKey);
if (fromKey == null) {
return EmptyImmutableSortedMap.forComparator(comparator());
}
}
return tailMap(fromKey);
}
private ImmutableSortedMap<K, V> newView(SortedMap<K, V> delegate) {
return newView(delegate, comparator);
}
private static <K, V> ImmutableSortedMap<K, V> newView(
SortedMap<K, V> delegate, Comparator<? super K> comparator) {
if (delegate.isEmpty()) {
return EmptyImmutableSortedMap.forComparator(comparator);
}
return new RegularImmutableSortedMap<K, V>(delegate, comparator);
}
/*
* We don't permit nulls, but we wrap every comparator with nullsFirst().
* Why? We want for queries like containsKey(null) to return false, but the
* GWT SortedMap implementation that we delegate to throws
* NullPointerException if the comparator does. Since our construction
* methods ensure that null is never present in the map, it's OK for the
* comparator to look for it wherever it wants.
*
* Note that we do NOT touch the comparator returned by comparator(), which
* should be identical to the one the user passed in. We touch only the
* "secret" comparator used by the delegate implementation.
*/
private static <K, V> SortedMap<K, V> newModifiableDelegate(Comparator<? super K> comparator) {
return newTreeMap(nullAccepting(comparator));
}
private static <E> Comparator<E> nullAccepting(Comparator<E> comparator) {
return Ordering.from(comparator).nullsFirst();
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import java.util.Comparator;
import java.util.TreeMap;
/**
* GWT emulated version of {@link EmptyImmutableSortedMap}.
*
* @author Chris Povirk
*/
final class EmptyImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> {
private EmptyImmutableSortedMap(Comparator<? super K> comparator) {
super(new TreeMap<K, V>(comparator), comparator);
}
@SuppressWarnings("unchecked")
private static final ImmutableSortedMap<Object, Object> NATURAL_EMPTY_MAP =
new EmptyImmutableSortedMap<Object, Object>(NATURAL_ORDER);
static <K, V> ImmutableSortedMap<K, V> forComparator(Comparator<? super K> comparator) {
if (comparator == NATURAL_ORDER) {
return (ImmutableSortedMap) NATURAL_EMPTY_MAP;
}
return new EmptyImmutableSortedMap<K, V>(comparator);
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.io.GwtWorkarounds.asCharInput;
import static com.google.common.io.GwtWorkarounds.stringBuilderOutput;
import static com.google.common.math.IntMath.divide;
import static com.google.common.math.IntMath.log2;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.io.GwtWorkarounds.ByteInput;
import com.google.common.io.GwtWorkarounds.ByteOutput;
import com.google.common.io.GwtWorkarounds.CharInput;
import com.google.common.io.GwtWorkarounds.CharOutput;
import java.io.IOException;
import java.util.Arrays;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* A binary encoding scheme for reversibly translating between byte sequences and printable ASCII
* strings. This class includes several constants for encoding schemes specified by <a
* href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression:
*
* <pre> {@code
* BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))}</pre>
*
* <p>returns the string {@code "MZXW6==="}, and <pre> {@code
* byte[] decoded = BaseEncoding.base32().decode("MZXW6===");}</pre>
*
* <p>...returns the ASCII bytes of the string {@code "foo"}.
*
* <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with
* RFC 4648. Decoding rejects characters in the wrong case, though padding is optional.
* To modify encoding and decoding behavior, use configuration methods to obtain a new encoding
* with modified behavior:
*
* <pre> {@code
* BaseEncoding.base16().lowerCase().decode("deadbeef");}</pre>
*
* <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect
* on the receiving instance; you must store and use the new encoding instance it returns, instead.
*
* <pre> {@code
* // Do NOT do this
* BaseEncoding hex = BaseEncoding.base16();
* hex.lowerCase(); // does nothing!
* return hex.decode("deadbeef"); // throws an IllegalArgumentException}</pre>
*
* <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to
* {@code x}, but the reverse does not necessarily hold.
*
* <p>
* <table>
* <tr>
* <th>Encoding
* <th>Alphabet
* <th>{@code char:byte} ratio
* <th>Default padding
* <th>Comments
* <tr>
* <td>{@link #base16()}
* <td>0-9 A-F
* <td>2.00
* <td>N/A
* <td>Traditional hexadecimal. Defaults to upper case.
* <tr>
* <td>{@link #base32()}
* <td>A-Z 2-7
* <td>1.60
* <td>=
* <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case.
* <tr>
* <td>{@link #base32Hex()}
* <td>0-9 A-V
* <td>1.60
* <td>=
* <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case.
* <tr>
* <td>{@link #base64()}
* <td>A-Z a-z 0-9 + /
* <td>1.33
* <td>=
* <td>
* <tr>
* <td>{@link #base64Url()}
* <td>A-Z a-z 0-9 - _
* <td>1.33
* <td>=
* <td>Safe to use as filenames, or to pass in URLs without escaping
* </table>
*
* <p>
* All instances of this class are immutable, so they may be stored safely as static constants.
*
* @author Louis Wasserman
* @since 14.0
*/
@Beta
@GwtCompatible(emulated = true)
public abstract class BaseEncoding {
// TODO(user): consider adding encodeTo(Appendable, byte[], [int, int])
BaseEncoding() {}
/**
* Exception indicating invalid base-encoded input encountered while decoding.
*
* @author Louis Wasserman
* @since 15.0
*/
public static final class DecodingException extends IOException {
DecodingException(String message) {
super(message);
}
DecodingException(Throwable cause) {
super(cause);
}
}
/**
* Encodes the specified byte array, and returns the encoded {@code String}.
*/
public String encode(byte[] bytes) {
return encode(checkNotNull(bytes), 0, bytes.length);
}
/**
* Encodes the specified range of the specified byte array, and returns the encoded
* {@code String}.
*/
public final String encode(byte[] bytes, int off, int len) {
checkNotNull(bytes);
checkPositionIndexes(off, off + len, bytes.length);
CharOutput result = stringBuilderOutput(maxEncodedSize(len));
ByteOutput byteOutput = encodingStream(result);
try {
for (int i = 0; i < len; i++) {
byteOutput.write(bytes[off + i]);
}
byteOutput.close();
} catch (IOException impossible) {
throw new AssertionError("impossible");
}
return result.toString();
}
// TODO(user): document the extent of leniency, probably after adding ignore(CharMatcher)
private static byte[] extract(byte[] result, int length) {
if (length == result.length) {
return result;
} else {
byte[] trunc = new byte[length];
System.arraycopy(result, 0, trunc, 0, length);
return trunc;
}
}
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}.
* This is the inverse operation to {@link #encode(byte[])}.
*
* @throws IllegalArgumentException if the input is not a valid encoded string according to this
* encoding.
*/
public final byte[] decode(CharSequence chars) {
try {
return decodeChecked(chars);
} catch (DecodingException badInput) {
throw new IllegalArgumentException(badInput);
}
}
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}.
* This is the inverse operation to {@link #encode(byte[])}.
*
* @throws DecodingException if the input is not a valid encoded string according to this
* encoding.
*/
final byte[] decodeChecked(CharSequence chars) throws DecodingException {
chars = padding().trimTrailingFrom(chars);
ByteInput decodedInput = decodingStream(asCharInput(chars));
byte[] tmp = new byte[maxDecodedSize(chars.length())];
int index = 0;
try {
for (int i = decodedInput.read(); i != -1; i = decodedInput.read()) {
tmp[index++] = (byte) i;
}
} catch (DecodingException badInput) {
throw badInput;
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return extract(tmp, index);
}
// Implementations for encoding/decoding
abstract int maxEncodedSize(int bytes);
abstract ByteOutput encodingStream(CharOutput charOutput);
abstract int maxDecodedSize(int chars);
abstract ByteInput decodingStream(CharInput charInput);
abstract CharMatcher padding();
// Modified encoding generators
/**
* Returns an encoding that behaves equivalently to this encoding, but omits any padding
* characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648
* section 3.2</a>, Padding of Encoded Data.
*/
@CheckReturnValue
public abstract BaseEncoding omitPadding();
/**
* Returns an encoding that behaves equivalently to this encoding, but uses an alternate character
* for padding.
*
* @throws IllegalArgumentException if this padding character is already used in the alphabet or a
* separator
*/
@CheckReturnValue
public abstract BaseEncoding withPadChar(char padChar);
/**
* Returns an encoding that behaves equivalently to this encoding, but adds a separator string
* after every {@code n} characters. Any occurrences of any characters that occur in the separator
* are skipped over in decoding.
*
* @throws IllegalArgumentException if any alphabet or padding characters appear in the separator
* string, or if {@code n <= 0}
* @throws UnsupportedOperationException if this encoding already uses a separator
*/
@CheckReturnValue
public abstract BaseEncoding withSeparator(String separator, int n);
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* uppercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
@CheckReturnValue
public abstract BaseEncoding upperCase();
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* lowercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
@CheckReturnValue
public abstract BaseEncoding lowerCase();
private static final BaseEncoding BASE64 = new StandardBaseEncoding(
"base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
/**
* The "base64" base encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding.
* (This is the same as the base 64 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64() {
return BASE64;
}
private static final BaseEncoding BASE64_URL = new StandardBaseEncoding(
"base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '=');
/**
* The "base64url" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding
* with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64."
* (This is the same as the base 64 encoding with URL and filename safe alphabet from <a
* href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64Url() {
return BASE64_URL;
}
private static final BaseEncoding BASE32 =
new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '=');
/**
* The "base32" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-6">RFC 4648 section 6</a>, Base 32 Encoding.
* (This is the same as the base 32 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32() {
return BASE32;
}
private static final BaseEncoding BASE32_HEX =
new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '=');
/**
* The "base32hex" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding
* with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548.
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32Hex() {
return BASE32_HEX;
}
private static final BaseEncoding BASE16 =
new StandardBaseEncoding("base16()", "0123456789ABCDEF", null);
/**
* The "base16" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-8">RFC 4648 section 8</a>, Base 16 Encoding.
* (This is the same as the base 16 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as
* "hexadecimal" format.
*
* <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and
* {@link #omitPadding()} have no effect.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base16() {
return BASE16;
}
private static final class Alphabet extends CharMatcher {
private final String name;
// this is meant to be immutable -- don't modify it!
private final char[] chars;
final int mask;
final int bitsPerChar;
final int charsPerChunk;
final int bytesPerChunk;
private final byte[] decodabet;
private final boolean[] validPadding;
Alphabet(String name, char[] chars) {
this.name = checkNotNull(name);
this.chars = checkNotNull(chars);
try {
this.bitsPerChar = log2(chars.length, UNNECESSARY);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
}
/*
* e.g. for base64, bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. This makes
* for the smallest chunk size that still has charsPerChunk * bitsPerChar be a multiple of 8.
*/
int gcd = Math.min(8, Integer.lowestOneBit(bitsPerChar));
this.charsPerChunk = 8 / gcd;
this.bytesPerChunk = bitsPerChar / gcd;
this.mask = chars.length - 1;
byte[] decodabet = new byte[Ascii.MAX + 1];
Arrays.fill(decodabet, (byte) -1);
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
checkArgument(CharMatcher.ASCII.matches(c), "Non-ASCII character: %s", c);
checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
decodabet[c] = (byte) i;
}
this.decodabet = decodabet;
boolean[] validPadding = new boolean[charsPerChunk];
for (int i = 0; i < bytesPerChunk; i++) {
validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
}
this.validPadding = validPadding;
}
char encode(int bits) {
return chars[bits];
}
boolean isValidPaddingStartPosition(int index) {
return validPadding[index % charsPerChunk];
}
int decode(char ch) throws IOException {
if (ch > Ascii.MAX || decodabet[ch] == -1) {
throw new DecodingException("Unrecognized character: " + ch);
}
return decodabet[ch];
}
private boolean hasLowerCase() {
for (char c : chars) {
if (Ascii.isLowerCase(c)) {
return true;
}
}
return false;
}
private boolean hasUpperCase() {
for (char c : chars) {
if (Ascii.isUpperCase(c)) {
return true;
}
}
return false;
}
Alphabet upperCase() {
if (!hasLowerCase()) {
return this;
} else {
checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet");
char[] upperCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
return new Alphabet(name + ".upperCase()", upperCased);
}
}
Alphabet lowerCase() {
if (!hasUpperCase()) {
return this;
} else {
checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet");
char[] lowerCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
return new Alphabet(name + ".lowerCase()", lowerCased);
}
}
@Override
public boolean matches(char c) {
return CharMatcher.ASCII.matches(c) && decodabet[c] != -1;
}
@Override
public String toString() {
return name;
}
}
static final class StandardBaseEncoding extends BaseEncoding {
// TODO(user): provide a useful toString
private final Alphabet alphabet;
@Nullable
private final Character paddingChar;
StandardBaseEncoding(String name, String alphabetChars, @Nullable Character paddingChar) {
this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
}
StandardBaseEncoding(Alphabet alphabet, @Nullable Character paddingChar) {
this.alphabet = checkNotNull(alphabet);
checkArgument(paddingChar == null || !alphabet.matches(paddingChar),
"Padding character %s was already in alphabet", paddingChar);
this.paddingChar = paddingChar;
}
@Override
CharMatcher padding() {
return (paddingChar == null) ? CharMatcher.NONE : CharMatcher.is(paddingChar.charValue());
}
@Override
int maxEncodedSize(int bytes) {
return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
}
@Override
ByteOutput encodingStream(final CharOutput out) {
checkNotNull(out);
return new ByteOutput() {
int bitBuffer = 0;
int bitBufferLength = 0;
int writtenChars = 0;
@Override
public void write(byte b) throws IOException {
bitBuffer <<= 8;
bitBuffer |= b & 0xFF;
bitBufferLength += 8;
while (bitBufferLength >= alphabet.bitsPerChar) {
int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar))
& alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
bitBufferLength -= alphabet.bitsPerChar;
}
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
if (bitBufferLength > 0) {
int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength))
& alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
if (paddingChar != null) {
while (writtenChars % alphabet.charsPerChunk != 0) {
out.write(paddingChar.charValue());
writtenChars++;
}
}
}
out.close();
}
};
}
@Override
int maxDecodedSize(int chars) {
return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L);
}
@Override
ByteInput decodingStream(final CharInput reader) {
checkNotNull(reader);
return new ByteInput() {
int bitBuffer = 0;
int bitBufferLength = 0;
int readChars = 0;
boolean hitPadding = false;
final CharMatcher paddingMatcher = padding();
@Override
public int read() throws IOException {
while (true) {
int readChar = reader.read();
if (readChar == -1) {
if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) {
throw new DecodingException("Invalid input length " + readChars);
}
return -1;
}
readChars++;
char ch = (char) readChar;
if (paddingMatcher.matches(ch)) {
if (!hitPadding
&& (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) {
throw new DecodingException("Padding cannot start at index " + readChars);
}
hitPadding = true;
} else if (hitPadding) {
throw new DecodingException(
"Expected padding character but found '" + ch + "' at index " + readChars);
} else {
bitBuffer <<= alphabet.bitsPerChar;
bitBuffer |= alphabet.decode(ch);
bitBufferLength += alphabet.bitsPerChar;
if (bitBufferLength >= 8) {
bitBufferLength -= 8;
return (bitBuffer >> bitBufferLength) & 0xFF;
}
}
}
}
@Override
public void close() throws IOException {
reader.close();
}
};
}
@Override
public BaseEncoding omitPadding() {
return (paddingChar == null) ? this : new StandardBaseEncoding(alphabet, null);
}
@Override
public BaseEncoding withPadChar(char padChar) {
if (8 % alphabet.bitsPerChar == 0 ||
(paddingChar != null && paddingChar.charValue() == padChar)) {
return this;
} else {
return new StandardBaseEncoding(alphabet, padChar);
}
}
@Override
public BaseEncoding withSeparator(String separator, int afterEveryChars) {
checkNotNull(separator);
checkArgument(padding().or(alphabet).matchesNoneOf(separator),
"Separator cannot contain alphabet or padding characters");
return new SeparatedBaseEncoding(this, separator, afterEveryChars);
}
private transient BaseEncoding upperCase;
private transient BaseEncoding lowerCase;
@Override
public BaseEncoding upperCase() {
BaseEncoding result = upperCase;
if (result == null) {
Alphabet upper = alphabet.upperCase();
result = upperCase =
(upper == alphabet) ? this : new StandardBaseEncoding(upper, paddingChar);
}
return result;
}
@Override
public BaseEncoding lowerCase() {
BaseEncoding result = lowerCase;
if (result == null) {
Alphabet lower = alphabet.lowerCase();
result = lowerCase =
(lower == alphabet) ? this : new StandardBaseEncoding(lower, paddingChar);
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BaseEncoding.");
builder.append(alphabet.toString());
if (8 % alphabet.bitsPerChar != 0) {
if (paddingChar == null) {
builder.append(".omitPadding()");
} else {
builder.append(".withPadChar(").append(paddingChar).append(')');
}
}
return builder.toString();
}
}
static CharInput ignoringInput(final CharInput delegate, final CharMatcher toIgnore) {
checkNotNull(delegate);
checkNotNull(toIgnore);
return new CharInput() {
@Override
public int read() throws IOException {
int readChar;
do {
readChar = delegate.read();
} while (readChar != -1 && toIgnore.matches((char) readChar));
return readChar;
}
@Override
public void close() throws IOException {
delegate.close();
}
};
}
static CharOutput separatingOutput(
final CharOutput delegate, final String separator, final int afterEveryChars) {
checkNotNull(delegate);
checkNotNull(separator);
checkArgument(afterEveryChars > 0);
return new CharOutput() {
int charsUntilSeparator = afterEveryChars;
@Override
public void write(char c) throws IOException {
if (charsUntilSeparator == 0) {
for (int i = 0; i < separator.length(); i++) {
delegate.write(separator.charAt(i));
}
charsUntilSeparator = afterEveryChars;
}
delegate.write(c);
charsUntilSeparator--;
}
@Override
public void flush() throws IOException {
delegate.flush();
}
@Override
public void close() throws IOException {
delegate.close();
}
};
}
static final class SeparatedBaseEncoding extends BaseEncoding {
private final BaseEncoding delegate;
private final String separator;
private final int afterEveryChars;
private final CharMatcher separatorChars;
SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) {
this.delegate = checkNotNull(delegate);
this.separator = checkNotNull(separator);
this.afterEveryChars = afterEveryChars;
checkArgument(
afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars);
this.separatorChars = CharMatcher.anyOf(separator).precomputed();
}
@Override
CharMatcher padding() {
return delegate.padding();
}
@Override
int maxEncodedSize(int bytes) {
int unseparatedSize = delegate.maxEncodedSize(bytes);
return unseparatedSize + separator.length()
* divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR);
}
@Override
ByteOutput encodingStream(final CharOutput output) {
return delegate.encodingStream(separatingOutput(output, separator, afterEveryChars));
}
@Override
int maxDecodedSize(int chars) {
return delegate.maxDecodedSize(chars);
}
@Override
ByteInput decodingStream(final CharInput input) {
return delegate.decodingStream(ignoringInput(input, separatorChars));
}
@Override
public BaseEncoding omitPadding() {
return delegate.omitPadding().withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding withPadChar(char padChar) {
return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding withSeparator(String separator, int afterEveryChars) {
throw new UnsupportedOperationException("Already have a separator");
}
@Override
public BaseEncoding upperCase() {
return delegate.upperCase().withSeparator(separator, afterEveryChars);
}
@Override
public BaseEncoding lowerCase() {
return delegate.lowerCase().withSeparator(separator, afterEveryChars);
}
@Override
public String toString() {
return delegate.toString() +
".withSeparator(\"" + separator + "\", " + afterEveryChars + ")";
}
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.IOException;
/**
* Provides simple GWT-compatible substitutes for {@code InputStream}, {@code OutputStream},
* {@code Reader}, and {@code Writer} so that {@code BaseEncoding} can use streaming implementations
* while remaining GWT-compatible.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
final class GwtWorkarounds {
private GwtWorkarounds() {}
/**
* A GWT-compatible substitute for a {@code Reader}.
*/
interface CharInput {
int read() throws IOException;
void close() throws IOException;
}
/**
* Views a {@code CharSequence} as a {@code CharInput}.
*/
static CharInput asCharInput(final CharSequence chars) {
checkNotNull(chars);
return new CharInput() {
int index = 0;
@Override
public int read() {
if (index < chars.length()) {
return chars.charAt(index++);
} else {
return -1;
}
}
@Override
public void close() {
index = chars.length();
}
};
}
/**
* A GWT-compatible substitute for an {@code InputStream}.
*/
interface ByteInput {
int read() throws IOException;
void close() throws IOException;
}
/**
* A GWT-compatible substitute for an {@code OutputStream}.
*/
interface ByteOutput {
void write(byte b) throws IOException;
void flush() throws IOException;
void close() throws IOException;
}
/**
* A GWT-compatible substitute for a {@code Writer}.
*/
interface CharOutput {
void write(char c) throws IOException;
void flush() throws IOException;
void close() throws IOException;
}
/**
* Returns a {@code CharOutput} whose {@code toString()} method can be used
* to get the combined output.
*/
static CharOutput stringBuilderOutput(int initialSize) {
final StringBuilder builder = new StringBuilder(initialSize);
return new CharOutput() {
@Override
public void write(char c) {
builder.append(c);
}
@Override
public void flush() {}
@Override
public void close() {}
@Override
public String toString() {
return builder.toString();
}
};
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio.charset;
/**
* GWT emulation of {@link IllegalCharsetNameException}.
*
* @author Gregory Kick
*/
public class IllegalCharsetNameException extends IllegalArgumentException {
private final String charsetName;
public IllegalCharsetNameException(String charsetName) {
super(String.valueOf(charsetName));
this.charsetName = charsetName;
}
public String getCharsetName() {
return charsetName;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio.charset;
/**
* GWT emulation of {@link UnsupportedCharsetException}.
*
* @author Gregory Kick
*/
public class UnsupportedCharsetException extends IllegalArgumentException {
private final String charsetName;
public UnsupportedCharsetException(String charsetName) {
super(String.valueOf(charsetName));
this.charsetName = charsetName;
}
public String getCharsetName() {
return charsetName;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio.charset;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A minimal GWT emulation of {@link Charset}.
*
* @author Gregory Kick
*/
public abstract class Charset implements Comparable<Charset> {
private static final Charset UTF_8 = new Charset("UTF-8") {};
private static final SortedMap<String, Charset> AVAILABLE_CHARSETS =
new TreeMap<String, Charset>();
static {
AVAILABLE_CHARSETS.put(UTF_8.name(), UTF_8);
}
public static SortedMap<String, Charset> availableCharsets() {
return Collections.unmodifiableSortedMap(AVAILABLE_CHARSETS);
}
public static Charset forName(String charsetName) {
if (charsetName == null) {
throw new IllegalArgumentException("Null charset name");
}
int length = charsetName.length();
if (length == 0) {
throw new IllegalCharsetNameException(charsetName);
}
for (int i = 0; i < length; i++) {
char c = charsetName.charAt(i);
if ((c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| (c == '-' && i != 0)
|| (c == ':' && i != 0)
|| (c == '_' && i != 0)
|| (c == '.' && i != 0)) {
continue;
}
throw new IllegalCharsetNameException(charsetName);
}
Charset charset = AVAILABLE_CHARSETS.get(charsetName.toUpperCase());
if (charset != null) {
return charset;
}
throw new UnsupportedCharsetException(charsetName);
}
private final String name;
private Charset(String name) {
this.name = name;
}
public final String name() {
return name;
}
public final int compareTo(Charset that) {
return this.name.compareToIgnoreCase(that.name);
}
public final int hashCode() {
return name.hashCode();
}
public final boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Charset) {
Charset that = (Charset) o;
return this.name.equals(that.name);
} else {
return false;
}
}
public final String toString() {
return name;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.util.concurrent;
/**
* Emulation of Callable.
*
* @author Charles Fry
*/
public interface Callable<V> {
V call() throws Exception;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.