Use diamond operator when creating generic instances (#2104)

This commit is contained in:
Marcono1234 2022-04-18 00:27:21 +02:00 committed by GitHub
parent e82637c485
commit 4dda4ec5ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 252 additions and 263 deletions

View File

@ -53,7 +53,7 @@ public class GsonProguardExampleActivity extends Activity {
} }
private Cart buildCart() { private Cart buildCart() {
List<LineItem> lineItems = new ArrayList<LineItem>(); List<LineItem> lineItems = new ArrayList<>();
lineItems.add(new LineItem("hammer", 1, 12000000, "USD")); lineItems.add(new LineItem("hammer", 1, 12000000, "USD"));
return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111"); return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111");
} }

View File

@ -48,7 +48,7 @@ public final class GraphAdapterBuilder {
private final ConstructorConstructor constructorConstructor; private final ConstructorConstructor constructorConstructor;
public GraphAdapterBuilder() { public GraphAdapterBuilder() {
this.instanceCreators = new HashMap<Type, InstanceCreator<?>>(); this.instanceCreators = new HashMap<>();
this.constructorConstructor = new ConstructorConstructor(instanceCreators, true, Collections.<ReflectionAccessFilter>emptyList()); this.constructorConstructor = new ConstructorConstructor(instanceCreators, true, Collections.<ReflectionAccessFilter>emptyList());
} }
public GraphAdapterBuilder addType(Type type) { public GraphAdapterBuilder addType(Type type) {
@ -80,7 +80,7 @@ public final class GraphAdapterBuilder {
static class Factory implements TypeAdapterFactory, InstanceCreator { static class Factory implements TypeAdapterFactory, InstanceCreator {
private final Map<Type, InstanceCreator<?>> instanceCreators; private final Map<Type, InstanceCreator<?>> instanceCreators;
private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<Graph>(); private final ThreadLocal<Graph> graphThreadLocal = new ThreadLocal<>();
Factory(Map<Type, InstanceCreator<?>> instanceCreators) { Factory(Map<Type, InstanceCreator<?>> instanceCreators) {
this.instanceCreators = instanceCreators; this.instanceCreators = instanceCreators;
@ -121,7 +121,7 @@ public final class GraphAdapterBuilder {
@SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T @SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
Element<T> element = (Element<T>) graph.map.get(value); Element<T> element = (Element<T>) graph.map.get(value);
if (element == null) { if (element == null) {
element = new Element<T>(value, graph.nextName(), typeAdapter, null); element = new Element<>(value, graph.nextName(), typeAdapter, null);
graph.map.put(value, element); graph.map.put(value, element);
graph.queue.add(element); graph.queue.add(element);
} }
@ -178,7 +178,7 @@ public final class GraphAdapterBuilder {
currentName = name; currentName = name;
} }
JsonElement element = elementAdapter.read(in); JsonElement element = elementAdapter.read(in);
graph.map.put(name, new Element<T>(null, name, typeAdapter, element)); graph.map.put(name, new Element<>(null, name, typeAdapter, element));
} }
in.endObject(); in.endObject();
} else { } else {
@ -242,7 +242,7 @@ public final class GraphAdapterBuilder {
* The queue of elements to write during serialization. Unused during * The queue of elements to write during serialization. Unused during
* deserialization. * deserialization.
*/ */
private final Queue<Element> queue = new LinkedList<Element>(); private final Queue<Element> queue = new LinkedList<>();
/** /**
* The instance currently being deserialized. Used as a backdoor between * The instance currently being deserialized. Used as a backdoor between

View File

@ -19,7 +19,7 @@ public final class InterceptorFactory implements TypeAdapterFactory {
} }
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new InterceptorAdapter<T>(delegate, intercept); return new InterceptorAdapter<>(delegate, intercept);
} }
static class InterceptorAdapter<T> extends TypeAdapter<T> { static class InterceptorAdapter<T> extends TypeAdapter<T> {

View File

@ -38,7 +38,7 @@ public class PostConstructAdapterFactory implements TypeAdapterFactory {
if (m.isAnnotationPresent(PostConstruct.class)) { if (m.isAnnotationPresent(PostConstruct.class)) {
m.setAccessible(true); m.setAccessible(true);
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new PostConstructAdapter<T>(delegate, m); return new PostConstructAdapter<>(delegate, m);
} }
} }
} }

View File

@ -135,8 +135,8 @@ import com.google.gson.stream.JsonWriter;
public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType; private final Class<?> baseType;
private final String typeFieldName; private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
private final boolean maintainType; private final boolean maintainType;
private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boolean maintainType) { private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boolean maintainType) {
@ -154,7 +154,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* {@code maintainType} flag decide if the type will be stored in pojo or not. * {@code maintainType} flag decide if the type will be stored in pojo or not.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, maintainType); return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType);
} }
/** /**
@ -162,7 +162,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* typeFieldName} as the type field name. Type field names are case sensitive. * typeFieldName} as the type field name. Type field names are case sensitive.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, false); return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false);
} }
/** /**
@ -170,7 +170,7 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
* the type field name. * the type field name.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
return new RuntimeTypeAdapterFactory<T>(baseType, "type", false); return new RuntimeTypeAdapterFactory<>(baseType, "type", false);
} }
/** /**
@ -210,10 +210,8 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
} }
final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class);
final Map<String, TypeAdapter<?>> labelToDelegate final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
= new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
= new LinkedHashMap<Class<?>, TypeAdapter<?>>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate); labelToDelegate.put(entry.getKey(), delegate);

View File

@ -93,9 +93,9 @@ public final class GraphAdapterBuilderTest {
Type listOfListsType = new TypeToken<List<List<?>>>() {}.getType(); Type listOfListsType = new TypeToken<List<List<?>>>() {}.getType();
Type listOfAnyType = new TypeToken<List<?>>() {}.getType(); Type listOfAnyType = new TypeToken<List<?>>() {}.getType();
List<List<?>> listOfLists = new ArrayList<List<?>>(); List<List<?>> listOfLists = new ArrayList<>();
listOfLists.add(listOfLists); listOfLists.add(listOfLists);
listOfLists.add(new ArrayList<Object>()); listOfLists.add(new ArrayList<>());
GsonBuilder gsonBuilder = new GsonBuilder(); GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder() new GraphAdapterBuilder()
@ -187,7 +187,7 @@ public final class GraphAdapterBuilderTest {
static class Company { static class Company {
final String name; final String name;
final List<Employee> employees = new ArrayList<Employee>(); final List<Employee> employees = new ArrayList<>();
Company(String name) { Company(String name) {
this.name = name; this.name = name;
} }

View File

@ -128,9 +128,9 @@ public final class Gson {
* The proxy is wired up once the initial adapter has been created. * The proxy is wired up once the initial adapter has been created.
*/ */
private final ThreadLocal<Map<TypeToken<?>, FutureTypeAdapter<?>>> calls private final ThreadLocal<Map<TypeToken<?>, FutureTypeAdapter<?>>> calls
= new ThreadLocal<Map<TypeToken<?>, FutureTypeAdapter<?>>>(); = new ThreadLocal<>();
private final Map<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<TypeToken<?>, TypeAdapter<?>>(); private final Map<TypeToken<?>, TypeAdapter<?>> typeTokenCache = new ConcurrentHashMap<>();
private final ConstructorConstructor constructorConstructor; private final ConstructorConstructor constructorConstructor;
private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory; private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
@ -237,7 +237,7 @@ public final class Gson {
this.numberToNumberStrategy = numberToNumberStrategy; this.numberToNumberStrategy = numberToNumberStrategy;
this.reflectionFilters = reflectionFilters; this.reflectionFilters = reflectionFilters;
List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(); List<TypeAdapterFactory> factories = new ArrayList<>();
// built-in type adapters that cannot be overridden // built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY); factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
@ -453,7 +453,7 @@ public final class Gson {
out.endArray(); out.endArray();
} }
@Override public AtomicLongArray read(JsonReader in) throws IOException { @Override public AtomicLongArray read(JsonReader in) throws IOException {
List<Long> list = new ArrayList<Long>(); List<Long> list = new ArrayList<>();
in.beginArray(); in.beginArray();
while (in.hasNext()) { while (in.hasNext()) {
long value = longAdapter.read(in).longValue(); long value = longAdapter.read(in).longValue();
@ -486,7 +486,7 @@ public final class Gson {
Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get(); Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
boolean requiresThreadLocalCleanup = false; boolean requiresThreadLocalCleanup = false;
if (threadCalls == null) { if (threadCalls == null) {
threadCalls = new HashMap<TypeToken<?>, FutureTypeAdapter<?>>(); threadCalls = new HashMap<>();
calls.set(threadCalls); calls.set(threadCalls);
requiresThreadLocalCleanup = true; requiresThreadLocalCleanup = true;
} }
@ -498,7 +498,7 @@ public final class Gson {
} }
try { try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<T>(); FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
threadCalls.put(type, call); threadCalls.put(type, call);
for (TypeAdapterFactory factory : factories) { for (TypeAdapterFactory factory : factories) {

View File

@ -84,11 +84,10 @@ public final class GsonBuilder {
private Excluder excluder = Excluder.DEFAULT; private Excluder excluder = Excluder.DEFAULT;
private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT; private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT;
private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY; private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
private final Map<Type, InstanceCreator<?>> instanceCreators private final Map<Type, InstanceCreator<?>> instanceCreators = new HashMap<>();
= new HashMap<Type, InstanceCreator<?>>(); private final List<TypeAdapterFactory> factories = new ArrayList<>();
private final List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();
/** tree-style hierarchy factories. These come after factories for backwards compatibility. */ /** tree-style hierarchy factories. These come after factories for backwards compatibility. */
private final List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(); private final List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>();
private boolean serializeNulls = DEFAULT_SERIALIZE_NULLS; private boolean serializeNulls = DEFAULT_SERIALIZE_NULLS;
private String datePattern = DEFAULT_DATE_PATTERN; private String datePattern = DEFAULT_DATE_PATTERN;
private int dateStyle = DateFormat.DEFAULT; private int dateStyle = DateFormat.DEFAULT;
@ -102,7 +101,7 @@ public final class GsonBuilder {
private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE; private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE;
private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY; private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_TO_NUMBER_STRATEGY;
private ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY; private ToNumberStrategy numberToNumberStrategy = DEFAULT_NUMBER_TO_NUMBER_STRATEGY;
private final LinkedList<ReflectionAccessFilter> reflectionFilters = new LinkedList<ReflectionAccessFilter>(); private final LinkedList<ReflectionAccessFilter> reflectionFilters = new LinkedList<>();
/** /**
* Creates a GsonBuilder instance that can be used to build Gson with various configuration * Creates a GsonBuilder instance that can be used to build Gson with various configuration
@ -227,7 +226,7 @@ public final class GsonBuilder {
* .enableComplexMapKeySerialization() * .enableComplexMapKeySerialization()
* .create(); * .create();
* *
* Map<Point, String> original = new LinkedHashMap<Point, String>(); * Map<Point, String> original = new LinkedHashMap<>();
* original.put(new Point(5, 6), "a"); * original.put(new Point(5, 6), "a");
* original.put(new Point(8, 8), "b"); * original.put(new Point(8, 8), "b");
* System.out.println(gson.toJson(original, type)); * System.out.println(gson.toJson(original, type));
@ -254,7 +253,7 @@ public final class GsonBuilder {
* .enableComplexMapKeySerialization() * .enableComplexMapKeySerialization()
* .create(); * .create();
* *
* Map<Point, String> original = new LinkedHashMap<Point, String>(); * Map<Point, String> original = new LinkedHashMap<>();
* original.put(new Point(5, 6), "a"); * original.put(new Point(5, 6), "a");
* original.put(new Point(8, 8), "b"); * original.put(new Point(8, 8), "b");
* System.out.println(gson.toJson(original, type)); * System.out.println(gson.toJson(original, type));
@ -664,23 +663,23 @@ public final class GsonBuilder {
* @return an instance of Gson configured with the options currently set in this builder * @return an instance of Gson configured with the options currently set in this builder
*/ */
public Gson create() { public Gson create() {
List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(this.factories.size() + this.hierarchyFactories.size() + 3); List<TypeAdapterFactory> factories = new ArrayList<>(this.factories.size() + this.hierarchyFactories.size() + 3);
factories.addAll(this.factories); factories.addAll(this.factories);
Collections.reverse(factories); Collections.reverse(factories);
List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>(this.hierarchyFactories);
Collections.reverse(hierarchyFactories); Collections.reverse(hierarchyFactories);
factories.addAll(hierarchyFactories); factories.addAll(hierarchyFactories);
addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
return new Gson(excluder, fieldNamingPolicy, new HashMap<Type, InstanceCreator<?>>(instanceCreators), return new Gson(excluder, fieldNamingPolicy, new HashMap<>(instanceCreators),
serializeNulls, complexMapKeySerialization, serializeNulls, complexMapKeySerialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient,
serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy, serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy,
datePattern, dateStyle, timeStyle, new ArrayList<TypeAdapterFactory>(this.factories), datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories),
new ArrayList<TypeAdapterFactory>(this.hierarchyFactories), factories, new ArrayList<>(this.hierarchyFactories), factories,
objectToNumberStrategy, numberToNumberStrategy, new ArrayList<ReflectionAccessFilter>(reflectionFilters)); objectToNumberStrategy, numberToNumberStrategy, new ArrayList<>(reflectionFilters));
} }
private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle, private void addTypeAdaptersForDate(String datePattern, int dateStyle, int timeStyle,

View File

@ -37,11 +37,11 @@ public final class JsonArray extends JsonElement implements Iterable<JsonElement
* Creates an empty JsonArray. * Creates an empty JsonArray.
*/ */
public JsonArray() { public JsonArray() {
elements = new ArrayList<JsonElement>(); elements = new ArrayList<>();
} }
public JsonArray(int capacity) { public JsonArray(int capacity) {
elements = new ArrayList<JsonElement>(capacity); elements = new ArrayList<>(capacity);
} }
/** /**

View File

@ -30,8 +30,7 @@ import java.util.Set;
* @author Joel Leitch * @author Joel Leitch
*/ */
public final class JsonObject extends JsonElement { public final class JsonObject extends JsonElement {
private final LinkedTreeMap<String, JsonElement> members = private final LinkedTreeMap<String, JsonElement> members = new LinkedTreeMap<>();
new LinkedTreeMap<String, JsonElement>();
/** /**
* Creates a deep copy of this element and all its children * Creates a deep copy of this element and all its children

View File

@ -35,7 +35,7 @@ import com.google.gson.reflect.TypeToken;
* return null; * return null;
* } * }
* *
* final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); * final Map<String, T> lowercaseToConstant = new HashMap<>();
* for (T constant : rawType.getEnumConstants()) { * for (T constant : rawType.getEnumConstants()) {
* lowercaseToConstant.put(toLowercase(constant), constant); * lowercaseToConstant.put(toLowercase(constant), constant);
* } * }

View File

@ -277,25 +277,25 @@ public final class ConstructorConstructor {
if (SortedSet.class.isAssignableFrom(rawType)) { if (SortedSet.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new TreeSet<Object>(); return (T) new TreeSet<>();
} }
}; };
} else if (Set.class.isAssignableFrom(rawType)) { } else if (Set.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new LinkedHashSet<Object>(); return (T) new LinkedHashSet<>();
} }
}; };
} else if (Queue.class.isAssignableFrom(rawType)) { } else if (Queue.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new ArrayDeque<Object>(); return (T) new ArrayDeque<>();
} }
}; };
} else { } else {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new ArrayList<Object>(); return (T) new ArrayList<>();
} }
}; };
} }
@ -305,32 +305,32 @@ public final class ConstructorConstructor {
if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) { if (ConcurrentNavigableMap.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new ConcurrentSkipListMap<Object, Object>(); return (T) new ConcurrentSkipListMap<>();
} }
}; };
} else if (ConcurrentMap.class.isAssignableFrom(rawType)) { } else if (ConcurrentMap.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new ConcurrentHashMap<Object, Object>(); return (T) new ConcurrentHashMap<>();
} }
}; };
} else if (SortedMap.class.isAssignableFrom(rawType)) { } else if (SortedMap.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new TreeMap<Object, Object>(); return (T) new TreeMap<>();
} }
}; };
} else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom( } else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) { TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new LinkedHashMap<Object, Object>(); return (T) new LinkedHashMap<>();
} }
}; };
} else { } else {
return new ObjectConstructor<T>() { return new ObjectConstructor<T>() {
@Override public T construct() { @Override public T construct() {
return (T) new LinkedTreeMap<String, Object>(); return (T) new LinkedTreeMap<>();
} }
}; };
} }

View File

@ -97,12 +97,11 @@ public final class Excluder implements TypeAdapterFactory, Cloneable {
boolean serialization, boolean deserialization) { boolean serialization, boolean deserialization) {
Excluder result = clone(); Excluder result = clone();
if (serialization) { if (serialization) {
result.serializationStrategies = new ArrayList<ExclusionStrategy>(serializationStrategies); result.serializationStrategies = new ArrayList<>(serializationStrategies);
result.serializationStrategies.add(exclusionStrategy); result.serializationStrategies.add(exclusionStrategy);
} }
if (deserialization) { if (deserialization) {
result.deserializationStrategies result.deserializationStrategies = new ArrayList<>(deserializationStrategies);
= new ArrayList<ExclusionStrategy>(deserializationStrategies);
result.deserializationStrategies.add(exclusionStrategy); result.deserializationStrategies.add(exclusionStrategy);
} }
return result; return result;

View File

@ -52,7 +52,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
int modCount = 0; int modCount = 0;
// Used to preserve iteration order // Used to preserve iteration order
final Node<K, V> header = new Node<K, V>(); final Node<K, V> header = new Node<>();
/** /**
* Create a natural order, empty tree map whose keys must be mutually * Create a natural order, empty tree map whose keys must be mutually
@ -166,10 +166,10 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) { if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) {
throw new ClassCastException(key.getClass().getName() + " is not Comparable"); throw new ClassCastException(key.getClass().getName() + " is not Comparable");
} }
created = new Node<K, V>(nearest, key, header, header.prev); created = new Node<>(nearest, key, header, header.prev);
root = created; root = created;
} else { } else {
created = new Node<K, V>(nearest, key, header, header.prev); created = new Node<>(nearest, key, header, header.prev);
if (comparison < 0) { // nearest.key is higher if (comparison < 0) { // nearest.key is higher
nearest.left = created; nearest.left = created;
} else { // comparison > 0, nearest.key is lower } else { // comparison > 0, nearest.key is lower
@ -628,7 +628,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
* shouldn't use it. * shouldn't use it.
*/ */
private Object writeReplace() throws ObjectStreamException { private Object writeReplace() throws ObjectStreamException {
return new LinkedHashMap<K, V>(this); return new LinkedHashMap<>(this);
} }
private void readObject(ObjectInputStream in) throws IOException { private void readObject(ObjectInputStream in) throws IOException {

View File

@ -56,7 +56,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
public ArrayTypeAdapter(Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> componentType) { public ArrayTypeAdapter(Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> componentType) {
this.componentTypeAdapter = this.componentTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<E>(context, componentTypeAdapter, componentType); new TypeAdapterRuntimeTypeWrapper<>(context, componentTypeAdapter, componentType);
this.componentType = componentType; this.componentType = componentType;
} }
@ -66,7 +66,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
return null; return null;
} }
List<E> list = new ArrayList<E>(); List<E> list = new ArrayList<>();
in.beginArray(); in.beginArray();
while (in.hasNext()) { while (in.hasNext()) {
E instance = componentTypeAdapter.read(in); E instance = componentTypeAdapter.read(in);

View File

@ -66,7 +66,7 @@ public final class CollectionTypeAdapterFactory implements TypeAdapterFactory {
TypeAdapter<E> elementTypeAdapter, TypeAdapter<E> elementTypeAdapter,
ObjectConstructor<? extends Collection<E>> constructor) { ObjectConstructor<? extends Collection<E>> constructor) {
this.elementTypeAdapter = this.elementTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<E>(context, elementTypeAdapter, elementType); new TypeAdapterRuntimeTypeWrapper<>(context, elementTypeAdapter, elementType);
this.constructor = constructor; this.constructor = constructor;
} }

View File

@ -55,7 +55,7 @@ public final class DateTypeAdapter extends TypeAdapter<Date> {
* List of 1 or more different date formats used for de-serialization attempts. * List of 1 or more different date formats used for de-serialization attempts.
* The first of them (default US format) is used for serialization as well. * The first of them (default US format) is used for serialization as well.
*/ */
private final List<DateFormat> dateFormats = new ArrayList<DateFormat>(); private final List<DateFormat> dateFormats = new ArrayList<>();
public DateTypeAdapter() { public DateTypeAdapter() {
dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US)); dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US));

View File

@ -68,19 +68,19 @@ public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T>
} }
public final TypeAdapterFactory createAdapterFactory(String datePattern) { public final TypeAdapterFactory createAdapterFactory(String datePattern) {
return createFactory(new DefaultDateTypeAdapter<T>(this, datePattern)); return createFactory(new DefaultDateTypeAdapter<>(this, datePattern));
} }
public final TypeAdapterFactory createAdapterFactory(int style) { public final TypeAdapterFactory createAdapterFactory(int style) {
return createFactory(new DefaultDateTypeAdapter<T>(this, style)); return createFactory(new DefaultDateTypeAdapter<>(this, style));
} }
public final TypeAdapterFactory createAdapterFactory(int dateStyle, int timeStyle) { public final TypeAdapterFactory createAdapterFactory(int dateStyle, int timeStyle) {
return createFactory(new DefaultDateTypeAdapter<T>(this, dateStyle, timeStyle)); return createFactory(new DefaultDateTypeAdapter<>(this, dateStyle, timeStyle));
} }
public final TypeAdapterFactory createDefaultsAdapterFactory() { public final TypeAdapterFactory createDefaultsAdapterFactory() {
return createFactory(new DefaultDateTypeAdapter<T>(this, DateFormat.DEFAULT, DateFormat.DEFAULT)); return createFactory(new DefaultDateTypeAdapter<>(this, DateFormat.DEFAULT, DateFormat.DEFAULT));
} }
} }
@ -90,7 +90,7 @@ public final class DefaultDateTypeAdapter<T extends Date> extends TypeAdapter<T>
* List of 1 or more different date formats used for de-serialization attempts. * List of 1 or more different date formats used for de-serialization attempts.
* The first of them is used for serialization as well. * The first of them is used for serialization as well.
*/ */
private final List<DateFormat> dateFormats = new ArrayList<DateFormat>(); private final List<DateFormat> dateFormats = new ArrayList<>();
private DefaultDateTypeAdapter(DateType<T> dateType, String datePattern) { private DefaultDateTypeAdapter(DateType<T> dateType, String datePattern) {
this.dateType = $Gson$Preconditions.checkNotNull(dateType); this.dateType = $Gson$Preconditions.checkNotNull(dateType);

View File

@ -46,7 +46,7 @@ public final class JsonTreeWriter extends JsonWriter {
private static final JsonPrimitive SENTINEL_CLOSED = new JsonPrimitive("closed"); private static final JsonPrimitive SENTINEL_CLOSED = new JsonPrimitive("closed");
/** The JsonElements and JsonArrays under modification, outermost to innermost. */ /** The JsonElements and JsonArrays under modification, outermost to innermost. */
private final List<JsonElement> stack = new ArrayList<JsonElement>(); private final List<JsonElement> stack = new ArrayList<>();
/** The name for the next JSON object value. If non-null, the top of the stack is a JsonObject. */ /** The name for the next JSON object value. If non-null, the top of the stack is a JsonObject. */
private String pendingName; private String pendingName;

View File

@ -46,7 +46,7 @@ import java.util.Map;
* can be serialized as strings; this is insufficient for some key types. For * can be serialized as strings; this is insufficient for some key types. For
* example, consider a map whose keys are points on a grid. The default JSON * example, consider a map whose keys are points on a grid. The default JSON
* form encodes reasonably: <pre> {@code * form encodes reasonably: <pre> {@code
* Map<Point, String> original = new LinkedHashMap<Point, String>(); * Map<Point, String> original = new LinkedHashMap<>();
* original.put(new Point(5, 6), "a"); * original.put(new Point(5, 6), "a");
* original.put(new Point(8, 8), "b"); * original.put(new Point(8, 8), "b");
* System.out.println(gson.toJson(original, type)); * System.out.println(gson.toJson(original, type));
@ -151,9 +151,9 @@ public final class MapTypeAdapterFactory implements TypeAdapterFactory {
Type valueType, TypeAdapter<V> valueTypeAdapter, Type valueType, TypeAdapter<V> valueTypeAdapter,
ObjectConstructor<? extends Map<K, V>> constructor) { ObjectConstructor<? extends Map<K, V>> constructor) {
this.keyTypeAdapter = this.keyTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<K>(context, keyTypeAdapter, keyType); new TypeAdapterRuntimeTypeWrapper<>(context, keyTypeAdapter, keyType);
this.valueTypeAdapter = this.valueTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<V>(context, valueTypeAdapter, valueType); new TypeAdapterRuntimeTypeWrapper<>(context, valueTypeAdapter, valueType);
this.constructor = constructor; this.constructor = constructor;
} }
@ -212,9 +212,9 @@ public final class MapTypeAdapterFactory implements TypeAdapterFactory {
} }
boolean hasComplexKeys = false; boolean hasComplexKeys = false;
List<JsonElement> keys = new ArrayList<JsonElement>(map.size()); List<JsonElement> keys = new ArrayList<>(map.size());
List<V> values = new ArrayList<V>(map.size()); List<V> values = new ArrayList<>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) { for (Map.Entry<K, V> entry : map.entrySet()) {
JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey()); JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
keys.add(keyElement); keys.add(keyElement);

View File

@ -74,7 +74,7 @@ public final class ObjectTypeAdapter extends TypeAdapter<Object> {
JsonToken token = in.peek(); JsonToken token = in.peek();
switch (token) { switch (token) {
case BEGIN_ARRAY: case BEGIN_ARRAY:
List<Object> list = new ArrayList<Object>(); List<Object> list = new ArrayList<>();
in.beginArray(); in.beginArray();
while (in.hasNext()) { while (in.hasNext()) {
list.add(read(in)); list.add(read(in));
@ -83,7 +83,7 @@ public final class ObjectTypeAdapter extends TypeAdapter<Object> {
return list; return list;
case BEGIN_OBJECT: case BEGIN_OBJECT:
Map<String, Object> map = new LinkedTreeMap<String, Object>(); Map<String, Object> map = new LinkedTreeMap<>();
in.beginObject(); in.beginObject();
while (in.hasNext()) { while (in.hasNext()) {
map.put(in.nextName(), read(in)); map.put(in.nextName(), read(in));

View File

@ -90,7 +90,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
return Collections.singletonList(serializedName); return Collections.singletonList(serializedName);
} }
List<String> fieldNames = new ArrayList<String>(alternates.length + 1); List<String> fieldNames = new ArrayList<>(alternates.length + 1);
fieldNames.add(serializedName); fieldNames.add(serializedName);
for (String alternate : alternates) { for (String alternate : alternates) {
fieldNames.add(alternate); fieldNames.add(alternate);
@ -113,7 +113,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
boolean blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE; boolean blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE;
ObjectConstructor<T> constructor = constructorConstructor.get(type); ObjectConstructor<T> constructor = constructorConstructor.get(type);
return new Adapter<T>(constructor, getBoundFields(gson, type, raw, blockInaccessible)); return new Adapter<>(constructor, getBoundFields(gson, type, raw, blockInaccessible));
} }
private static void checkAccessible(Object object, Field field) { private static void checkAccessible(Object object, Field field) {
@ -174,7 +174,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
} }
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw, boolean blockInaccessible) { private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw, boolean blockInaccessible) {
Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); Map<String, BoundField> result = new LinkedHashMap<>();
if (raw.isInterface()) { if (raw.isInterface()) {
return result; return result;
} }

View File

@ -145,7 +145,7 @@ public final class TreeTypeAdapter<T> extends TypeAdapter<T> {
? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType() ? exactType.equals(type) || matchRawType && exactType.getType() == type.getRawType()
: hierarchyType.isAssignableFrom(type.getRawType()); : hierarchyType.isAssignableFrom(type.getRawType());
return matches return matches
? new TreeTypeAdapter<T>((JsonSerializer<T>) serializer, ? new TreeTypeAdapter<>((JsonSerializer<T>) serializer,
(JsonDeserializer<T>) deserializer, gson, type, this) (JsonDeserializer<T>) deserializer, gson, type, this)
: null; : null;
} }

View File

@ -278,7 +278,7 @@ public final class TypeAdapters {
public static final TypeAdapter<AtomicIntegerArray> ATOMIC_INTEGER_ARRAY = new TypeAdapter<AtomicIntegerArray>() { public static final TypeAdapter<AtomicIntegerArray> ATOMIC_INTEGER_ARRAY = new TypeAdapter<AtomicIntegerArray>() {
@Override public AtomicIntegerArray read(JsonReader in) throws IOException { @Override public AtomicIntegerArray read(JsonReader in) throws IOException {
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
in.beginArray(); in.beginArray();
while (in.hasNext()) { while (in.hasNext()) {
try { try {
@ -774,9 +774,9 @@ public final class TypeAdapters {
= newTypeHierarchyFactory(JsonElement.class, JSON_ELEMENT); = newTypeHierarchyFactory(JsonElement.class, JSON_ELEMENT);
private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> { private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
private final Map<String, T> nameToConstant = new HashMap<String, T>(); private final Map<String, T> nameToConstant = new HashMap<>();
private final Map<String, T> stringToConstant = new HashMap<String, T>(); private final Map<String, T> stringToConstant = new HashMap<>();
private final Map<T, String> constantToName = new HashMap<T, String>(); private final Map<T, String> constantToName = new HashMap<>();
public EnumTypeAdapter(final Class<T> classOfT) { public EnumTypeAdapter(final Class<T> classOfT) {
try { try {
@ -786,7 +786,7 @@ public final class TypeAdapters {
Field[] constantFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() { Field[] constantFields = AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
@Override public Field[] run() { @Override public Field[] run() {
Field[] fields = classOfT.getDeclaredFields(); Field[] fields = classOfT.getDeclaredFields();
ArrayList<Field> constantFieldsList = new ArrayList<Field>(fields.length); ArrayList<Field> constantFieldsList = new ArrayList<>(fields.length);
for (Field f : fields) { for (Field f : fields) {
if (f.isEnumConstant()) { if (f.isEnumConstant()) {
constantFieldsList.add(f); constantFieldsList.add(f);

View File

@ -221,14 +221,14 @@ public class TypeToken<T> {
} }
for (Type itype : clazz.getGenericInterfaces()) { for (Type itype : clazz.getGenericInterfaces()) {
if (isAssignableFrom(itype, to, new HashMap<String, Type>(typeVarMap))) { if (isAssignableFrom(itype, to, new HashMap<>(typeVarMap))) {
return true; return true;
} }
} }
// Interfaces didn't work, try the superclass. // Interfaces didn't work, try the superclass.
Type sType = clazz.getGenericSuperclass(); Type sType = clazz.getGenericSuperclass();
return isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap)); return isAssignableFrom(sType, to, new HashMap<>(typeVarMap));
} }
/** /**
@ -293,14 +293,14 @@ public class TypeToken<T> {
* Gets type literal for the given {@code Type} instance. * Gets type literal for the given {@code Type} instance.
*/ */
public static TypeToken<?> get(Type type) { public static TypeToken<?> get(Type type) {
return new TypeToken<Object>(type); return new TypeToken<>(type);
} }
/** /**
* Gets type literal for the given {@code Class} instance. * Gets type literal for the given {@code Class} instance.
*/ */
public static <T> TypeToken<T> get(Class<T> type) { public static <T> TypeToken<T> get(Class<T> type) {
return new TypeToken<T>(type); return new TypeToken<>(type);
} }
/** /**
@ -308,13 +308,13 @@ public class TypeToken<T> {
* {@code rawType}. * {@code rawType}.
*/ */
public static TypeToken<?> getParameterized(Type rawType, Type... typeArguments) { public static TypeToken<?> getParameterized(Type rawType, Type... typeArguments) {
return new TypeToken<Object>($Gson$Types.newParameterizedTypeWithOwner(null, rawType, typeArguments)); return new TypeToken<>($Gson$Types.newParameterizedTypeWithOwner(null, rawType, typeArguments));
} }
/** /**
* Gets type literal for the array type whose elements are all instances of {@code componentType}. * Gets type literal for the array type whose elements are all instances of {@code componentType}.
*/ */
public static TypeToken<?> getArray(Type componentType) { public static TypeToken<?> getArray(Type componentType) {
return new TypeToken<Object>($Gson$Types.arrayOf(componentType)); return new TypeToken<>($Gson$Types.arrayOf(componentType));
} }
} }

View File

@ -95,7 +95,7 @@ import java.util.Arrays;
* } * }
* *
* public List<Message> readMessagesArray(JsonReader reader) throws IOException { * public List<Message> readMessagesArray(JsonReader reader) throws IOException {
* List<Message> messages = new ArrayList<Message>(); * List<Message> messages = new ArrayList<>();
* *
* reader.beginArray(); * reader.beginArray();
* while (reader.hasNext()) { * while (reader.hasNext()) {
@ -131,7 +131,7 @@ import java.util.Arrays;
* } * }
* *
* public List<Double> readDoublesArray(JsonReader reader) throws IOException { * public List<Double> readDoublesArray(JsonReader reader) throws IOException {
* List<Double> doubles = new ArrayList<Double>(); * List<Double> doubles = new ArrayList<>();
* *
* reader.beginArray(); * reader.beginArray();
* while (reader.hasNext()) { * while (reader.hasNext()) {

View File

@ -32,7 +32,7 @@ public class DefaultMapJsonSerializerTest extends TestCase {
private Gson gson = new Gson(); private Gson gson = new Gson();
public void testEmptyMapNoTypeSerialization() { public void testEmptyMapNoTypeSerialization() {
Map<String, String> emptyMap = new HashMap<String, String>(); Map<String, String> emptyMap = new HashMap<>();
JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass()); JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
assertTrue(element instanceof JsonObject); assertTrue(element instanceof JsonObject);
JsonObject emptyMapJsonObject = (JsonObject) element; JsonObject emptyMapJsonObject = (JsonObject) element;
@ -41,7 +41,7 @@ public class DefaultMapJsonSerializerTest extends TestCase {
public void testEmptyMapSerialization() { public void testEmptyMapSerialization() {
Type mapType = new TypeToken<Map<String, String>>() { }.getType(); Type mapType = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> emptyMap = new HashMap<String, String>(); Map<String, String> emptyMap = new HashMap<>();
JsonElement element = gson.toJsonTree(emptyMap, mapType); JsonElement element = gson.toJsonTree(emptyMap, mapType);
assertTrue(element instanceof JsonObject); assertTrue(element instanceof JsonObject);
@ -51,7 +51,7 @@ public class DefaultMapJsonSerializerTest extends TestCase {
public void testNonEmptyMapSerialization() { public void testNonEmptyMapSerialization() {
Type mapType = new TypeToken<Map<String, String>>() { }.getType(); Type mapType = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> myMap = new HashMap<String, String>(); Map<String, String> myMap = new HashMap<>();
String key = "key1"; String key = "key1";
myMap.put(key, "value1"); myMap.put(key, "value1");
Gson gson = new Gson(); Gson gson = new Gson();

View File

@ -43,7 +43,7 @@ public final class JavaSerializationTest extends TestCase {
Map<String, Integer> serialized = serializedCopy(map); Map<String, Integer> serialized = serializedCopy(map);
assertEquals(map, serialized); assertEquals(map, serialized);
// Also check that the iteration order is retained. // Also check that the iteration order is retained.
assertEquals(Arrays.asList("b", "c", "a"), new ArrayList<String>(serialized.keySet())); assertEquals(Arrays.asList("b", "c", "a"), new ArrayList<>(serialized.keySet()));
} }
public void testListIsSerializable() throws Exception { public void testListIsSerializable() throws Exception {

View File

@ -40,13 +40,13 @@ public final class ObjectTypeAdapterTest extends TestCase {
} }
public void testSerializeNullValue() throws Exception { public void testSerializeNullValue() throws Exception {
Map<String, Object> map = new LinkedHashMap<String, Object>(); Map<String, Object> map = new LinkedHashMap<>();
map.put("a", null); map.put("a", null);
assertEquals("{'a':null}", adapter.toJson(map).replace('"', '\'')); assertEquals("{'a':null}", adapter.toJson(map).replace('"', '\''));
} }
public void testDeserializeNullValue() throws Exception { public void testDeserializeNullValue() throws Exception {
Map<String, Object> map = new LinkedHashMap<String, Object>(); Map<String, Object> map = new LinkedHashMap<>();
map.put("a", null); map.put("a", null);
assertEquals(map, adapter.fromJson("{\"a\":null}")); assertEquals(map, adapter.fromJson("{\"a\":null}"));
} }

View File

@ -119,7 +119,7 @@ public class ParameterizedTypeFixtures {
this.instanceOfT = instanceOfT; this.instanceOfT = instanceOfT;
} }
@Override public MyParameterizedType<T> createInstance(Type type) { @Override public MyParameterizedType<T> createInstance(Type type) {
return new MyParameterizedType<T>(instanceOfT); return new MyParameterizedType<>(instanceOfT);
} }
} }
@ -171,7 +171,7 @@ public class ParameterizedTypeFixtures {
PrimitiveTypeAdapter typeAdapter = new PrimitiveTypeAdapter(); PrimitiveTypeAdapter typeAdapter = new PrimitiveTypeAdapter();
value = (T) typeAdapter.adaptType(value, rawType); value = (T) typeAdapter.adaptType(value, rawType);
} }
return new MyParameterizedType<T>(value); return new MyParameterizedType<>(value);
} }
} }
} }

View File

@ -152,7 +152,7 @@ public class ArrayTest extends TestCase {
for (int i = 0; i < arraySize; ++i) { for (int i = 0; i < arraySize; ++i) {
int startValue = (3 * i) + 1; int startValue = (3 * i) + 1;
sb.append('[').append(startValue).append(',').append(startValue + 1).append(']'); sb.append('[').append(startValue).append(',').append(startValue + 1).append(']');
ArrayList<Integer> tmpList = new ArrayList<Integer>(); ArrayList<Integer> tmpList = new ArrayList<>();
tmpList.add(startValue); tmpList.add(startValue);
tmpList.add(startValue + 1); tmpList.add(startValue + 1);
arrayOfCollection[i] = tmpList; arrayOfCollection[i] = tmpList;

View File

@ -112,7 +112,7 @@ public class CircularReferenceTest extends TestCase {
} }
private static class ContainsReferenceToSelfType { private static class ContainsReferenceToSelfType {
Collection<ContainsReferenceToSelfType> children = new ArrayList<ContainsReferenceToSelfType>(); Collection<ContainsReferenceToSelfType> children = new ArrayList<>();
} }
private static class ClassWithSelfReference { private static class ClassWithSelfReference {

View File

@ -91,7 +91,7 @@ public class CollectionTest extends TestCase {
} }
public void testLinkedListSerialization() { public void testLinkedListSerialization() {
List<String> list = new LinkedList<String>(); List<String> list = new LinkedList<>();
list.add("a1"); list.add("a1");
list.add("a2"); list.add("a2");
Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType(); Type linkedListType = new TypeToken<LinkedList<String>>() {}.getType();
@ -109,7 +109,7 @@ public class CollectionTest extends TestCase {
} }
public void testQueueSerialization() { public void testQueueSerialization() {
Queue<String> queue = new LinkedList<String>(); Queue<String> queue = new LinkedList<>();
queue.add("a1"); queue.add("a1");
queue.add("a2"); queue.add("a2");
Type queueType = new TypeToken<Queue<String>>() {}.getType(); Type queueType = new TypeToken<Queue<String>>() {}.getType();
@ -161,7 +161,7 @@ public class CollectionTest extends TestCase {
} }
public void testNullsInListSerialization() { public void testNullsInListSerialization() {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
list.add("foo"); list.add("foo");
list.add(null); list.add(null);
list.add("bar"); list.add("bar");
@ -172,7 +172,7 @@ public class CollectionTest extends TestCase {
} }
public void testNullsInListDeserialization() { public void testNullsInListDeserialization() {
List<String> expected = new ArrayList<String>(); List<String> expected = new ArrayList<>();
expected.add("foo"); expected.add("foo");
expected.add(null); expected.add(null);
expected.add("bar"); expected.add("bar");
@ -185,7 +185,7 @@ public class CollectionTest extends TestCase {
} }
public void testCollectionOfObjectSerialization() { public void testCollectionOfObjectSerialization() {
List<Object> target = new ArrayList<Object>(); List<Object> target = new ArrayList<>();
target.add("Hello"); target.add("Hello");
target.add("World"); target.add("World");
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
@ -195,7 +195,7 @@ public class CollectionTest extends TestCase {
} }
public void testCollectionOfObjectWithNullSerialization() { public void testCollectionOfObjectWithNullSerialization() {
List<Object> target = new ArrayList<Object>(); List<Object> target = new ArrayList<>();
target.add("Hello"); target.add("Hello");
target.add(null); target.add(null);
target.add("World"); target.add("World");
@ -206,14 +206,14 @@ public class CollectionTest extends TestCase {
} }
public void testCollectionOfStringsSerialization() { public void testCollectionOfStringsSerialization() {
List<String> target = new ArrayList<String>(); List<String> target = new ArrayList<>();
target.add("Hello"); target.add("Hello");
target.add("World"); target.add("World");
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target)); assertEquals("[\"Hello\",\"World\"]", gson.toJson(target));
} }
public void testCollectionOfBagOfPrimitivesSerialization() { public void testCollectionOfBagOfPrimitivesSerialization() {
List<BagOfPrimitives> target = new ArrayList<BagOfPrimitives>(); List<BagOfPrimitives> target = new ArrayList<>();
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah"); BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB"); BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB");
target.add(objA); target.add(objA);
@ -297,7 +297,7 @@ public class CollectionTest extends TestCase {
} }
public void testWildcardCollectionField() throws Exception { public void testWildcardCollectionField() throws Exception {
Collection<BagOfPrimitives> collection = new ArrayList<BagOfPrimitives>(); Collection<BagOfPrimitives> collection = new ArrayList<>();
BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah"); BagOfPrimitives objA = new BagOfPrimitives(3L, 1, true, "blah");
BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB"); BagOfPrimitives objB = new BagOfPrimitives(2L, 6, false, "blahB");
collection.add(objA); collection.add(objA);
@ -340,7 +340,7 @@ public class CollectionTest extends TestCase {
} }
static class HasArrayListField { static class HasArrayListField {
ArrayList<Long> longs = new ArrayList<Long>(); ArrayList<Long> longs = new ArrayList<>();
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -377,7 +377,7 @@ public class CollectionTest extends TestCase {
} }
} }
public void testSetSerialization() { public void testSetSerialization() {
Set<Entry> set = new HashSet<Entry>(); Set<Entry> set = new HashSet<>();
set.add(new Entry(1)); set.add(new Entry(1));
set.add(new Entry(2)); set.add(new Entry(2));
String json = gson.toJson(set); String json = gson.toJson(set);

View File

@ -314,7 +314,7 @@ public class CustomTypeAdaptersTest extends TestCase {
.create(); .create();
Type setType = new TypeToken<Set<StringHolder>>() {}.getType(); Type setType = new TypeToken<Set<StringHolder>>() {}.getType();
StringHolder holder = new StringHolder("Jacob", "Tomaw"); StringHolder holder = new StringHolder("Jacob", "Tomaw");
Set<StringHolder> setOfHolders = new HashSet<StringHolder>(); Set<StringHolder> setOfHolders = new HashSet<>();
setOfHolders.add(holder); setOfHolders.add(holder);
String json = gson.toJson(setOfHolders, setType); String json = gson.toJson(setOfHolders, setType);
assertTrue(json.contains("Jacob:Tomaw")); assertTrue(json.contains("Jacob:Tomaw"));
@ -326,7 +326,7 @@ public class CustomTypeAdaptersTest extends TestCase {
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter()) .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
.create(); .create();
StringHolder holder = new StringHolder("Jacob", "Tomaw"); StringHolder holder = new StringHolder("Jacob", "Tomaw");
Set<StringHolder> setOfHolders = new HashSet<StringHolder>(); Set<StringHolder> setOfHolders = new HashSet<>();
setOfHolders.add(holder); setOfHolders.add(holder);
String json = gson.toJson(setOfHolders); String json = gson.toJson(setOfHolders);
assertTrue(json.contains("Jacob:Tomaw")); assertTrue(json.contains("Jacob:Tomaw"));
@ -352,7 +352,7 @@ public class CustomTypeAdaptersTest extends TestCase {
.create(); .create();
Type mapType = new TypeToken<Map<String,StringHolder>>() {}.getType(); Type mapType = new TypeToken<Map<String,StringHolder>>() {}.getType();
StringHolder holder = new StringHolder("Jacob", "Tomaw"); StringHolder holder = new StringHolder("Jacob", "Tomaw");
Map<String, StringHolder> mapOfHolders = new HashMap<String, StringHolder>(); Map<String, StringHolder> mapOfHolders = new HashMap<>();
mapOfHolders.put("foo", holder); mapOfHolders.put("foo", holder);
String json = gson.toJson(mapOfHolders, mapType); String json = gson.toJson(mapOfHolders, mapType);
assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\""));
@ -364,7 +364,7 @@ public class CustomTypeAdaptersTest extends TestCase {
.registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter()) .registerTypeAdapter(StringHolder.class, new StringHolderTypeAdapter())
.create(); .create();
StringHolder holder = new StringHolder("Jacob", "Tomaw"); StringHolder holder = new StringHolder("Jacob", "Tomaw");
Map<String, StringHolder> mapOfHolders = new HashMap<String, StringHolder>(); Map<String, StringHolder> mapOfHolders = new HashMap<>();
mapOfHolders.put("foo", holder); mapOfHolders.put("foo", holder);
String json = gson.toJson(mapOfHolders); String json = gson.toJson(mapOfHolders);
assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\"")); assertTrue(json.contains("\"foo\":\"Jacob:Tomaw\""));

View File

@ -293,7 +293,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
public void testSetSerialization() throws Exception { public void testSetSerialization() throws Exception {
Gson gson = new Gson(); Gson gson = new Gson();
HashSet<String> s = new HashSet<String>(); HashSet<String> s = new HashSet<>();
s.add("blah"); s.add("blah");
String json = gson.toJson(s); String json = gson.toJson(s);
assertEquals("[\"blah\"]", json); assertEquals("[\"blah\"]", json);
@ -619,7 +619,7 @@ public class DefaultTypeAdaptersTest extends TestCase {
} }
public void testTreeSetSerialization() { public void testTreeSetSerialization() {
TreeSet<String> treeSet = new TreeSet<String>(); TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Value1"); treeSet.add("Value1");
String json = gson.toJson(treeSet); String json = gson.toJson(treeSet);
assertEquals("[\"Value1\"]", json); assertEquals("[\"Value1\"]", json);

View File

@ -50,7 +50,7 @@ public class DelegateTypeAdapterTest extends TestCase {
} }
public void testDelegateInvoked() { public void testDelegateInvoked() {
List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>(); List<BagOfPrimitives> bags = new ArrayList<>();
for (int i = 0; i < 10; ++i) { for (int i = 0; i < 10; ++i) {
bags.add(new BagOfPrimitives(i, i, i % 2 == 0, String.valueOf(i))); bags.add(new BagOfPrimitives(i, i, i % 2 == 0, String.valueOf(i)));
} }

View File

@ -66,7 +66,7 @@ public class EnumTest extends TestCase {
public void testCollectionOfEnumsSerialization() { public void testCollectionOfEnumsSerialization() {
Type type = new TypeToken<Collection<MyEnum>>() {}.getType(); Type type = new TypeToken<Collection<MyEnum>>() {}.getType();
Collection<MyEnum> target = new ArrayList<MyEnum>(); Collection<MyEnum> target = new ArrayList<>();
target.add(MyEnum.VALUE1); target.add(MyEnum.VALUE1);
target.add(MyEnum.VALUE2); target.add(MyEnum.VALUE2);
String expectedJson = "[\"VALUE1\",\"VALUE2\"]"; String expectedJson = "[\"VALUE1\",\"VALUE2\"]";
@ -133,7 +133,7 @@ public class EnumTest extends TestCase {
} }
public void testEnumSubclassAsParameterizedType() { public void testEnumSubclassAsParameterizedType() {
Collection<Roshambo> list = new ArrayList<Roshambo>(); Collection<Roshambo> list = new ArrayList<>();
list.add(Roshambo.ROCK); list.add(Roshambo.ROCK);
list.add(Roshambo.PAPER); list.add(Roshambo.PAPER);
@ -164,7 +164,7 @@ public class EnumTest extends TestCase {
} }
public void testEnumMap() throws Exception { public void testEnumMap() throws Exception {
EnumMap<MyEnum, String> map = new EnumMap<MyEnum, String>(MyEnum.class); EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
map.put(MyEnum.VALUE1, "test"); map.put(MyEnum.VALUE1, "test");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"VALUE1\":\"test\"}", json); assertEquals("{\"VALUE1\":\"test\"}", json);

View File

@ -47,7 +47,7 @@ public class EscapingTest extends TestCase {
} }
public void testEscapeAllHtmlCharacters() { public void testEscapeAllHtmlCharacters() {
List<String> strings = new ArrayList<String>(); List<String> strings = new ArrayList<>();
strings.add("<"); strings.add("<");
strings.add(">"); strings.add(">");
strings.add("="); strings.add("=");

View File

@ -87,7 +87,7 @@ public class InheritanceTest extends TestCase {
} }
public void testClassWithBaseCollectionFieldSerialization() { public void testClassWithBaseCollectionFieldSerialization() {
Collection<Base> baseClasses = new ArrayList<Base>(); Collection<Base> baseClasses = new ArrayList<>();
baseClasses.add(new Sub()); baseClasses.add(new Sub());
baseClasses.add(new Sub()); baseClasses.add(new Sub());
ClassWithBaseCollectionField sub = new ClassWithBaseCollectionField(baseClasses); ClassWithBaseCollectionField sub = new ClassWithBaseCollectionField(baseClasses);
@ -151,22 +151,22 @@ public class InheritanceTest extends TestCase {
} }
public void testSubInterfacesOfCollectionSerialization() throws Exception { public void testSubInterfacesOfCollectionSerialization() throws Exception {
List<Integer> list = new LinkedList<Integer>(); List<Integer> list = new LinkedList<>();
list.add(0); list.add(0);
list.add(1); list.add(1);
list.add(2); list.add(2);
list.add(3); list.add(3);
Queue<Long> queue = new LinkedList<Long>(); Queue<Long> queue = new LinkedList<>();
queue.add(0L); queue.add(0L);
queue.add(1L); queue.add(1L);
queue.add(2L); queue.add(2L);
queue.add(3L); queue.add(3L);
Set<Float> set = new TreeSet<Float>(); Set<Float> set = new TreeSet<>();
set.add(0.1F); set.add(0.1F);
set.add(0.2F); set.add(0.2F);
set.add(0.3F); set.add(0.3F);
set.add(0.4F); set.add(0.4F);
SortedSet<Character> sortedSet = new TreeSet<Character>(); SortedSet<Character> sortedSet = new TreeSet<>();
sortedSet.add('a'); sortedSet.add('a');
sortedSet.add('b'); sortedSet.add('b');
sortedSet.add('c'); sortedSet.add('c');

View File

@ -91,7 +91,7 @@ public class InstanceCreatorTest extends TestCase {
class SubArrayList<T> extends ArrayList<T> {} class SubArrayList<T> extends ArrayList<T> {}
InstanceCreator<List<String>> listCreator = new InstanceCreator<List<String>>() { InstanceCreator<List<String>> listCreator = new InstanceCreator<List<String>>() {
@Override public List<String> createInstance(Type type) { @Override public List<String> createInstance(Type type) {
return new SubArrayList<String>(); return new SubArrayList<>();
} }
}; };
Type listOfStringType = new TypeToken<List<String>>() {}.getType(); Type listOfStringType = new TypeToken<List<String>>() {}.getType();

View File

@ -137,8 +137,8 @@ public final class JsonAdapterSerializerDeserializerTest extends TestCase {
@JsonAdapter(BaseStringAdapter.class) Base<String> a; @JsonAdapter(BaseStringAdapter.class) Base<String> a;
@JsonAdapter(BaseIntegerAdapter.class) Base<Integer> b; @JsonAdapter(BaseIntegerAdapter.class) Base<Integer> b;
Container(String a, int b) { Container(String a, int b) {
this.a = new Base<String>(a); this.a = new Base<>(a);
this.b = new Base<Integer>(b); this.b = new Base<>(b);
} }
} }

View File

@ -34,7 +34,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
Map<Point, String> original = new LinkedHashMap<Point, String>(); Map<Point, String> original = new LinkedHashMap<>();
original.put(new Point(5, 5), "a"); original.put(new Point(5, 5), "a");
original.put(new Point(8, 8), "b"); original.put(new Point(8, 8), "b");
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
@ -42,7 +42,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type)); assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
// test that registering a type adapter for one map doesn't interfere with others // test that registering a type adapter for one map doesn't interfere with others
Map<String, Boolean> otherMap = new LinkedHashMap<String, Boolean>(); Map<String, Boolean> otherMap = new LinkedHashMap<>();
otherMap.put("t", true); otherMap.put("t", true);
otherMap.put("f", false); otherMap.put("f", false);
assertEquals("{\"t\":true,\"f\":false}", assertEquals("{\"t\":true,\"f\":false}",
@ -58,7 +58,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
Map<Number, String> original = new LinkedHashMap<Number, String>(); Map<Number, String> original = new LinkedHashMap<>();
original.put(1.0D, "a"); original.put(1.0D, "a");
original.put(1.0F, "b"); original.put(1.0F, "b");
try { try {
@ -88,7 +88,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization() .enableComplexMapKeySerialization()
.create(); .create();
Map<Point, String> original = new LinkedHashMap<Point, String>(); Map<Point, String> original = new LinkedHashMap<>();
original.put(new Point(6, 5), "abc"); original.put(new Point(6, 5), "abc");
original.put(new Point(1, 8), "def"); original.put(new Point(1, 8), "def");
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
@ -98,7 +98,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
public void testMapWithTypeVariableSerialization() { public void testMapWithTypeVariableSerialization() {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
PointWithProperty<Point> map = new PointWithProperty<Point>(); PointWithProperty<Point> map = new PointWithProperty<>();
map.map.put(new Point(2, 3), new Point(4, 5)); map.map.put(new Point(2, 3), new Point(4, 5));
Type type = new TypeToken<PointWithProperty<Point>>(){}.getType(); Type type = new TypeToken<PointWithProperty<Point>>(){}.getType();
String json = gson.toJson(map, type); String json = gson.toJson(map, type);
@ -136,6 +136,6 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
} }
static class PointWithProperty<T> { static class PointWithProperty<T> {
Map<Point, T> map = new HashMap<Point, T>(); Map<Point, T> map = new HashMap<>();
} }
} }

View File

@ -61,7 +61,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerialization() { public void testMapSerialization() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1); map.put("a", 1);
map.put("b", 2); map.put("b", 2);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
@ -89,7 +89,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerializationEmpty() { public void testMapSerializationEmpty() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json); assertEquals("{}", json);
@ -102,7 +102,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerializationWithNullValue() { public void testMapSerializationWithNullValue() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put("abc", null); map.put("abc", null);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
@ -120,7 +120,7 @@ public class MapTest extends TestCase {
public void testMapSerializationWithNullValueButSerializeNulls() { public void testMapSerializationWithNullValueButSerializeNulls() {
gson = new GsonBuilder().serializeNulls().create(); gson = new GsonBuilder().serializeNulls().create();
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put("abc", null); map.put("abc", null);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
@ -129,7 +129,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerializationWithNullKey() { public void testMapSerializationWithNullKey() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put(null, 123); map.put(null, 123);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType(); Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
@ -151,7 +151,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerializationWithIntegerKeys() { public void testMapSerializationWithIntegerKeys() {
Map<Integer, String> map = new LinkedHashMap<Integer, String>(); Map<Integer, String> map = new LinkedHashMap<>();
map.put(123, "456"); map.put(123, "456");
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType(); Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap); String json = gson.toJson(map, typeOfMap);
@ -252,7 +252,7 @@ public class MapTest extends TestCase {
} }
public void testParameterizedMapSubclassSerialization() { public void testParameterizedMapSubclassSerialization() {
MyParameterizedMap<String, String> map = new MyParameterizedMap<String, String>(10); MyParameterizedMap<String, String> map = new MyParameterizedMap<>(10);
map.put("a", "b"); map.put("a", "b");
Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType(); Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType();
String json = gson.toJson(map, type); String json = gson.toJson(map, type);
@ -309,7 +309,7 @@ public class MapTest extends TestCase {
} }
}).create(); }).create();
Map<String, Long> src = new LinkedHashMap<String, Long>(); Map<String, Long> src = new LinkedHashMap<>();
src.put("one", 1L); src.put("one", 1L);
src.put("two", 2L); src.put("two", 2L);
src.put("three", 3L); src.put("three", 3L);
@ -321,7 +321,7 @@ public class MapTest extends TestCase {
* Created in response to http://code.google.com/p/google-gson/issues/detail?id=99 * Created in response to http://code.google.com/p/google-gson/issues/detail?id=99
*/ */
private static class ClassWithAMap { private static class ClassWithAMap {
Map<String, String> map = new TreeMap<String, String>(); Map<String, String> map = new TreeMap<>();
} }
/** /**
@ -350,8 +350,7 @@ public class MapTest extends TestCase {
} }
public void testMapSerializationWithWildcardValues() { public void testMapSerializationWithWildcardValues() {
Map<String, ? extends Collection<? extends Integer>> map = Map<String, ? extends Collection<? extends Integer>> map = new LinkedHashMap<>();
new LinkedHashMap<String, Collection<Integer>>();
map.put("test", null); map.put("test", null);
Type typeOfMap = Type typeOfMap =
new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType(); new TypeToken<Map<String, ? extends Collection<? extends Integer>>>() {}.getType();
@ -379,8 +378,8 @@ public class MapTest extends TestCase {
* From bug report http://code.google.com/p/google-gson/issues/detail?id=95 * From bug report http://code.google.com/p/google-gson/issues/detail?id=95
*/ */
public void testMapOfMapSerialization() { public void testMapOfMapSerialization() {
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); Map<String, Map<String, String>> map = new HashMap<>();
Map<String, String> nestedMap = new HashMap<String, String>(); Map<String, String> nestedMap = new HashMap<>();
nestedMap.put("1", "1"); nestedMap.put("1", "1");
nestedMap.put("2", "2"); nestedMap.put("2", "2");
map.put("nestedMap", nestedMap); map.put("nestedMap", nestedMap);
@ -406,7 +405,7 @@ public class MapTest extends TestCase {
* From bug report http://code.google.com/p/google-gson/issues/detail?id=178 * From bug report http://code.google.com/p/google-gson/issues/detail?id=178
*/ */
public void testMapWithQuotes() { public void testMapWithQuotes() {
Map<String, String> map = new HashMap<String, String>(); Map<String, String> map = new HashMap<>();
map.put("a\"b", "c\"d"); map.put("a\"b", "c\"d");
String json = gson.toJson(map); String json = gson.toJson(map);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json); assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
@ -416,7 +415,7 @@ public class MapTest extends TestCase {
* From issue 227. * From issue 227.
*/ */
public void testWriteMapsWithEmptyStringKey() { public void testWriteMapsWithEmptyStringKey() {
Map<String, Boolean> map = new HashMap<String, Boolean>(); Map<String, Boolean> map = new HashMap<>();
map.put("", true); map.put("", true);
assertEquals("{\"\":true}", gson.toJson(map)); assertEquals("{\"\":true}", gson.toJson(map));
@ -431,11 +430,11 @@ public class MapTest extends TestCase {
* From bug report http://code.google.com/p/google-gson/issues/detail?id=204 * From bug report http://code.google.com/p/google-gson/issues/detail?id=204
*/ */
public void testSerializeMaps() { public void testSerializeMaps() {
Map<String, Object> map = new LinkedHashMap<String, Object>(); Map<String, Object> map = new LinkedHashMap<>();
map.put("a", 12); map.put("a", 12);
map.put("b", null); map.put("b", null);
LinkedHashMap<String, Object> innerMap = new LinkedHashMap<String, Object>(); LinkedHashMap<String, Object> innerMap = new LinkedHashMap<>();
innerMap.put("test", 1); innerMap.put("test", 1);
innerMap.put("TestStringArray", new String[] { "one", "two" }); innerMap.put("TestStringArray", new String[] { "one", "two" });
map.put("c", innerMap); map.put("c", innerMap);
@ -443,8 +442,8 @@ public class MapTest extends TestCase {
assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
new GsonBuilder().serializeNulls().create().toJson(map)); new GsonBuilder().serializeNulls().create().toJson(map));
assertEquals("{\n \"a\": 12,\n \"b\": null,\n \"c\": " assertEquals("{\n \"a\": 12,\n \"b\": null,\n \"c\": "
+ "{\n \"test\": 1,\n \"TestStringArray\": " + "{\n \"test\": 1,\n \"TestStringArray\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}", + "[\n \"one\",\n \"two\"\n ]\n }\n}",
new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map)); new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map));
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}", assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
new GsonBuilder().create().toJson(map)); new GsonBuilder().create().toJson(map));
@ -530,7 +529,7 @@ public class MapTest extends TestCase {
} }
public void testComplexKeysSerialization() { public void testComplexKeysSerialization() {
Map<Point, String> map = new LinkedHashMap<Point, String>(); Map<Point, String> map = new LinkedHashMap<>();
map.put(new Point(2, 3), "a"); map.put(new Point(2, 3), "a");
map.put(new Point(5, 7), "b"); map.put(new Point(5, 7), "b");
String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}"; String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}";
@ -549,7 +548,7 @@ public class MapTest extends TestCase {
public void testStringKeyDeserialization() { public void testStringKeyDeserialization() {
String json = "{'2,3':'a','5,7':'b'}"; String json = "{'2,3':'a','5,7':'b'}";
Map<String, String> map = new LinkedHashMap<String, String>(); Map<String, String> map = new LinkedHashMap<>();
map.put("2,3", "a"); map.put("2,3", "a");
map.put("5,7", "b"); map.put("5,7", "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType())); assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
@ -557,7 +556,7 @@ public class MapTest extends TestCase {
public void testNumberKeyDeserialization() { public void testNumberKeyDeserialization() {
String json = "{'2.3':'a','5.7':'b'}"; String json = "{'2.3':'a','5.7':'b'}";
Map<Double, String> map = new LinkedHashMap<Double, String>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
map.put(5.7, "b"); map.put(5.7, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType())); assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
@ -565,7 +564,7 @@ public class MapTest extends TestCase {
public void testBooleanKeyDeserialization() { public void testBooleanKeyDeserialization() {
String json = "{'true':'a','false':'b'}"; String json = "{'true':'a','false':'b'}";
Map<Boolean, String> map = new LinkedHashMap<Boolean, String>(); Map<Boolean, String> map = new LinkedHashMap<>();
map.put(true, "a"); map.put(true, "a");
map.put(false, "b"); map.put(false, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType())); assertEquals(map, gson.fromJson(json, new TypeToken<Map<Boolean, String>>() {}.getType()));
@ -598,7 +597,7 @@ public class MapTest extends TestCase {
} }
private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) { private <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) {
Map<K, V> result = new LinkedHashMap<K, V>(); Map<K, V> result = new LinkedHashMap<>();
result.put(key1, value1); result.put(key1, value1);
result.put(key2, value2); result.put(key2, value2);
return result; return result;
@ -606,7 +605,7 @@ public class MapTest extends TestCase {
public void testMapNamePromotionWithJsonElementReader() { public void testMapNamePromotionWithJsonElementReader() {
String json = "{'2.3':'a'}"; String json = "{'2.3':'a'}";
Map<Double, String> map = new LinkedHashMap<Double, String>(); Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a"); map.put(2.3, "a");
JsonElement tree = JsonParser.parseString(json); JsonElement tree = JsonParser.parseString(json);
assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType())); assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
@ -635,8 +634,8 @@ public class MapTest extends TestCase {
} }
static final class MapClass { static final class MapClass {
private final Map<String, TestTypes.Base> bases = new HashMap<String, TestTypes.Base>(); private final Map<String, TestTypes.Base> bases = new HashMap<>();
private final Map<String, TestTypes.Sub> subs = new HashMap<String, TestTypes.Sub>(); private final Map<String, TestTypes.Sub> subs = new HashMap<>();
public final void addBase(String name, TestTypes.Base value) { public final void addBase(String name, TestTypes.Base value) {
bases.put(name, value); bases.put(name, value);

View File

@ -49,7 +49,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
} }
public void testListOfSubclassFields() { public void testListOfSubclassFields() {
Collection<Base> list = new ArrayList<Base>(); Collection<Base> list = new ArrayList<>();
list.add(new Base(1)); list.add(new Base(1));
list.add(new Sub(2, 3)); list.add(new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null); ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null);
@ -59,7 +59,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
} }
public void testMapOfSubclassFields() { public void testMapOfSubclassFields() {
Map<String, Base> map = new HashMap<String, Base>(); Map<String, Base> map = new HashMap<>();
map.put("base", new Base(1)); map.put("base", new Base(1));
map.put("sub", new Sub(2, 3)); map.put("sub", new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map); ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map);
@ -75,7 +75,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
*/ */
public void testParameterizedSubclassFields() { public void testParameterizedSubclassFields() {
ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields( ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
new ParameterizedSub<String>("one", "two")); new ParameterizedSub<>("one", "two"));
String json = gson.toJson(target); String json = gson.toJson(target);
assertTrue(json.contains("\"t\":\"one\"")); assertTrue(json.contains("\"t\":\"one\""));
assertFalse(json.contains("\"s\"")); assertFalse(json.contains("\"s\""));
@ -86,9 +86,9 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
* the declared type * the declared type
*/ */
public void testListOfParameterizedSubclassFields() { public void testListOfParameterizedSubclassFields() {
Collection<ParameterizedBase<String>> list = new ArrayList<ParameterizedBase<String>>(); Collection<ParameterizedBase<String>> list = new ArrayList<>();
list.add(new ParameterizedBase<String>("one")); list.add(new ParameterizedBase<>("one"));
list.add(new ParameterizedSub<String>("two", "three")); list.add(new ParameterizedSub<>("two", "three"));
ClassWithContainersOfParameterizedBaseFields target = ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(list, null); new ClassWithContainersOfParameterizedBaseFields(list, null);
String json = gson.toJson(target); String json = gson.toJson(target);
@ -101,9 +101,9 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
* declared type * declared type
*/ */
public void testMapOfParameterizedSubclassFields() { public void testMapOfParameterizedSubclassFields() {
Map<String, ParameterizedBase<String>> map = new HashMap<String, ParameterizedBase<String>>(); Map<String, ParameterizedBase<String>> map = new HashMap<>();
map.put("base", new ParameterizedBase<String>("one")); map.put("base", new ParameterizedBase<>("one"));
map.put("sub", new ParameterizedSub<String>("two", "three")); map.put("sub", new ParameterizedSub<>("two", "three"));
ClassWithContainersOfParameterizedBaseFields target = ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(null, map); new ClassWithContainersOfParameterizedBaseFields(null, map);
JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject(); JsonObject json = gson.toJsonTree(target).getAsJsonObject().get("map").getAsJsonObject();

View File

@ -117,7 +117,7 @@ public class ObjectTest extends TestCase {
} }
public void testClassWithTransientFieldsSerialization() throws Exception { public void testClassWithTransientFieldsSerialization() throws Exception {
ClassWithTransientFields<Long> target = new ClassWithTransientFields<Long>(1L); ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
assertEquals(target.getExpectedJson(), gson.toJson(target)); assertEquals(target.getExpectedJson(), gson.toJson(target));
} }
@ -259,7 +259,7 @@ public class ObjectTest extends TestCase {
} }
private static class ClassWithCollectionField { private static class ClassWithCollectionField {
Collection<String> children = new ArrayList<String>(); Collection<String> children = new ArrayList<>();
} }
public void testPrimitiveArrayInAnObjectDeserialization() throws Exception { public void testPrimitiveArrayInAnObjectDeserialization() throws Exception {
@ -497,7 +497,7 @@ public class ObjectTest extends TestCase {
} }
public class HasObjectMap { public class HasObjectMap {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<>();
} }
static final class Department { static final class Department {
@ -506,7 +506,7 @@ public class ObjectTest extends TestCase {
} }
static final class Product { static final class Product {
private List<String> attributes = new ArrayList<String>(); private List<String> attributes = new ArrayList<>();
private List<Department> departments = new ArrayList<Department>(); private List<Department> departments = new ArrayList<>();
} }
} }

View File

@ -52,7 +52,7 @@ public class ParameterizedTypesTest extends TestCase {
} }
public void testParameterizedTypesSerialization() throws Exception { public void testParameterizedTypesSerialization() throws Exception {
MyParameterizedType<Integer> src = new MyParameterizedType<Integer>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
String json = gson.toJson(src, typeOfSrc); String json = gson.toJson(src, typeOfSrc);
assertEquals(src.getExpectedJson(), json); assertEquals(src.getExpectedJson(), json);
@ -60,11 +60,11 @@ public class ParameterizedTypesTest extends TestCase {
public void testParameterizedTypeDeserialization() throws Exception { public void testParameterizedTypeDeserialization() throws Exception {
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();
MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<BagOfPrimitives>(bag); MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType(); Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
BagOfPrimitives bagDefaultInstance = new BagOfPrimitives(); BagOfPrimitives bagDefaultInstance = new BagOfPrimitives();
Gson gson = new GsonBuilder().registerTypeAdapter( Gson gson = new GsonBuilder().registerTypeAdapter(
expectedType, new MyParameterizedTypeInstanceCreator<BagOfPrimitives>(bagDefaultInstance)) expectedType, new MyParameterizedTypeInstanceCreator<>(bagDefaultInstance))
.create(); .create();
String json = expected.getExpectedJson(); String json = expected.getExpectedJson();
@ -74,8 +74,7 @@ public class ParameterizedTypesTest extends TestCase {
public void testTypesWithMultipleParametersSerialization() throws Exception { public void testTypesWithMultipleParametersSerialization() throws Exception {
MultiParameters<Integer, Float, Double, String, BagOfPrimitives> src = MultiParameters<Integer, Float, Double, String, BagOfPrimitives> src =
new MultiParameters<Integer, Float, Double, String, BagOfPrimitives>(10, 1.0F, 2.1D, new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
"abc", new BagOfPrimitives());
Type typeOfSrc = new TypeToken<MultiParameters<Integer, Float, Double, String, Type typeOfSrc = new TypeToken<MultiParameters<Integer, Float, Double, String,
BagOfPrimitives>>() {}.getType(); BagOfPrimitives>>() {}.getType();
String json = gson.toJson(src, typeOfSrc); String json = gson.toJson(src, typeOfSrc);
@ -92,8 +91,7 @@ public class ParameterizedTypesTest extends TestCase {
MultiParameters<Integer, Float, Double, String, BagOfPrimitives> target = MultiParameters<Integer, Float, Double, String, BagOfPrimitives> target =
gson.fromJson(json, typeOfTarget); gson.fromJson(json, typeOfTarget);
MultiParameters<Integer, Float, Double, String, BagOfPrimitives> expected = MultiParameters<Integer, Float, Double, String, BagOfPrimitives> expected =
new MultiParameters<Integer, Float, Double, String, BagOfPrimitives>(10, 1.0F, 2.1D, new MultiParameters<>(10, 1.0F, 2.1D, "abc", new BagOfPrimitives());
"abc", new BagOfPrimitives());
assertEquals(expected, target); assertEquals(expected, target);
} }
@ -104,11 +102,11 @@ public class ParameterizedTypesTest extends TestCase {
.registerTypeAdapter(ptIntegerType, new MyParameterizedTypeAdapter<Integer>()) .registerTypeAdapter(ptIntegerType, new MyParameterizedTypeAdapter<Integer>())
.registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>()) .registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>())
.create(); .create();
MyParameterizedType<Integer> intTarget = new MyParameterizedType<Integer>(10); MyParameterizedType<Integer> intTarget = new MyParameterizedType<>(10);
String json = gson.toJson(intTarget, ptIntegerType); String json = gson.toJson(intTarget, ptIntegerType);
assertEquals(MyParameterizedTypeAdapter.<Integer>getExpectedJson(intTarget), json); assertEquals(MyParameterizedTypeAdapter.<Integer>getExpectedJson(intTarget), json);
MyParameterizedType<String> stringTarget = new MyParameterizedType<String>("abc"); MyParameterizedType<String> stringTarget = new MyParameterizedType<>("abc");
json = gson.toJson(stringTarget, ptStringType); json = gson.toJson(stringTarget, ptStringType);
assertEquals(MyParameterizedTypeAdapter.<String>getExpectedJson(stringTarget), json); assertEquals(MyParameterizedTypeAdapter.<String>getExpectedJson(stringTarget), json);
} }
@ -119,17 +117,16 @@ public class ParameterizedTypesTest extends TestCase {
Gson gson = new GsonBuilder().registerTypeAdapter( Gson gson = new GsonBuilder().registerTypeAdapter(
ptIntegerType, new MyParameterizedTypeAdapter<Integer>()) ptIntegerType, new MyParameterizedTypeAdapter<Integer>())
.registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>()) .registerTypeAdapter(ptStringType, new MyParameterizedTypeAdapter<String>())
.registerTypeAdapter(ptStringType, new MyParameterizedTypeInstanceCreator<String>("")) .registerTypeAdapter(ptStringType, new MyParameterizedTypeInstanceCreator<>(""))
.registerTypeAdapter(ptIntegerType, .registerTypeAdapter(ptIntegerType, new MyParameterizedTypeInstanceCreator<>(0))
new MyParameterizedTypeInstanceCreator<Integer>(0))
.create(); .create();
MyParameterizedType<Integer> src = new MyParameterizedType<Integer>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
String json = MyParameterizedTypeAdapter.<Integer>getExpectedJson(src); String json = MyParameterizedTypeAdapter.<Integer>getExpectedJson(src);
MyParameterizedType<Integer> intTarget = gson.fromJson(json, ptIntegerType); MyParameterizedType<Integer> intTarget = gson.fromJson(json, ptIntegerType);
assertEquals(10, intTarget.value.intValue()); assertEquals(10, intTarget.value.intValue());
MyParameterizedType<String> srcStr = new MyParameterizedType<String>("abc"); MyParameterizedType<String> srcStr = new MyParameterizedType<>("abc");
json = MyParameterizedTypeAdapter.<String>getExpectedJson(srcStr); json = MyParameterizedTypeAdapter.<String>getExpectedJson(srcStr);
MyParameterizedType<String> stringTarget = gson.fromJson(json, ptStringType); MyParameterizedType<String> stringTarget = gson.fromJson(json, ptStringType);
assertEquals("abc", stringTarget.value); assertEquals("abc", stringTarget.value);
@ -137,7 +134,7 @@ public class ParameterizedTypesTest extends TestCase {
public void testParameterizedTypesWithWriterSerialization() throws Exception { public void testParameterizedTypesWithWriterSerialization() throws Exception {
Writer writer = new StringWriter(); Writer writer = new StringWriter();
MyParameterizedType<Integer> src = new MyParameterizedType<Integer>(10); MyParameterizedType<Integer> src = new MyParameterizedType<>(10);
Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<MyParameterizedType<Integer>>() {}.getType();
gson.toJson(src, typeOfSrc, writer); gson.toJson(src, typeOfSrc, writer);
assertEquals(src.getExpectedJson(), writer.toString()); assertEquals(src.getExpectedJson(), writer.toString());
@ -145,11 +142,11 @@ public class ParameterizedTypesTest extends TestCase {
public void testParameterizedTypeWithReaderDeserialization() throws Exception { public void testParameterizedTypeWithReaderDeserialization() throws Exception {
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();
MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<BagOfPrimitives>(bag); MyParameterizedType<BagOfPrimitives> expected = new MyParameterizedType<>(bag);
Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType(); Type expectedType = new TypeToken<MyParameterizedType<BagOfPrimitives>>() {}.getType();
BagOfPrimitives bagDefaultInstance = new BagOfPrimitives(); BagOfPrimitives bagDefaultInstance = new BagOfPrimitives();
Gson gson = new GsonBuilder().registerTypeAdapter( Gson gson = new GsonBuilder().registerTypeAdapter(
expectedType, new MyParameterizedTypeInstanceCreator<BagOfPrimitives>(bagDefaultInstance)) expectedType, new MyParameterizedTypeInstanceCreator<>(bagDefaultInstance))
.create(); .create();
Reader json = new StringReader(expected.getExpectedJson()); Reader json = new StringReader(expected.getExpectedJson());
@ -161,14 +158,14 @@ public class ParameterizedTypesTest extends TestCase {
public void testVariableTypeFieldsAndGenericArraysSerialization() throws Exception { public void testVariableTypeFieldsAndGenericArraysSerialization() throws Exception {
Integer obj = 0; Integer obj = 0;
Integer[] array = { 1, 2, 3 }; Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
list.add(4); list.add(4);
list.add(5); list.add(5);
List<Integer>[] arrayOfLists = new List[] { list, list }; List<Integer>[] arrayOfLists = new List[] { list, list };
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(obj, array, list, arrayOfLists, list, arrayOfLists); new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
assertEquals(objToSerialize.getExpectedJson(), json); assertEquals(objToSerialize.getExpectedJson(), json);
@ -178,14 +175,14 @@ public class ParameterizedTypesTest extends TestCase {
public void testVariableTypeFieldsAndGenericArraysDeserialization() throws Exception { public void testVariableTypeFieldsAndGenericArraysDeserialization() throws Exception {
Integer obj = 0; Integer obj = 0;
Integer[] array = { 1, 2, 3 }; Integer[] array = { 1, 2, 3 };
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
list.add(4); list.add(4);
list.add(5); list.add(5);
List<Integer>[] arrayOfLists = new List[] { list, list }; List<Integer>[] arrayOfLists = new List[] { list, list };
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(obj, array, list, arrayOfLists, list, arrayOfLists); new ObjectWithTypeVariables<>(obj, array, list, arrayOfLists, list, arrayOfLists);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
@ -195,7 +192,7 @@ public class ParameterizedTypesTest extends TestCase {
public void testVariableTypeDeserialization() throws Exception { public void testVariableTypeDeserialization() throws Exception {
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(0, null, null, null, null, null); new ObjectWithTypeVariables<>(0, null, null, null, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
@ -207,7 +204,7 @@ public class ParameterizedTypesTest extends TestCase {
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(null, array, null, null, null, null); new ObjectWithTypeVariables<>(null, array, null, null, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
@ -215,13 +212,13 @@ public class ParameterizedTypesTest extends TestCase {
} }
public void testParameterizedTypeWithVariableTypeDeserialization() throws Exception { public void testParameterizedTypeWithVariableTypeDeserialization() throws Exception {
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
list.add(4); list.add(4);
list.add(5); list.add(5);
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(null, null, list, null, null, null); new ObjectWithTypeVariables<>(null, null, list, null, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
@ -230,28 +227,28 @@ public class ParameterizedTypesTest extends TestCase {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testParameterizedTypeGenericArraysSerialization() throws Exception { public void testParameterizedTypeGenericArraysSerialization() throws Exception {
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
list.add(1); list.add(1);
list.add(2); list.add(2);
List<Integer>[] arrayOfLists = new List[] { list, list }; List<Integer>[] arrayOfLists = new List[] { list, list };
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(null, null, null, arrayOfLists, null, null); new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
assertEquals("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}", json); assertEquals("{\"arrayOfListOfTypeParameters\":[[1,2],[1,2]]}", json);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testParameterizedTypeGenericArraysDeserialization() throws Exception { public void testParameterizedTypeGenericArraysDeserialization() throws Exception {
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
list.add(1); list.add(1);
list.add(2); list.add(2);
List<Integer>[] arrayOfLists = new List[] { list, list }; List<Integer>[] arrayOfLists = new List[] { list, list };
Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType(); Type typeOfSrc = new TypeToken<ObjectWithTypeVariables<Integer>>() {}.getType();
ObjectWithTypeVariables<Integer> objToSerialize = ObjectWithTypeVariables<Integer> objToSerialize =
new ObjectWithTypeVariables<Integer>(null, null, null, arrayOfLists, null, null); new ObjectWithTypeVariables<>(null, null, null, arrayOfLists, null, null);
String json = gson.toJson(objToSerialize, typeOfSrc); String json = gson.toJson(objToSerialize, typeOfSrc);
ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc); ObjectWithTypeVariables<Integer> objAfterDeserialization = gson.fromJson(json, typeOfSrc);
@ -487,7 +484,7 @@ public class ParameterizedTypesTest extends TestCase {
} }
public void testDeepParameterizedTypeSerialization() { public void testDeepParameterizedTypeSerialization() {
Amount<MyQuantity> amount = new Amount<MyQuantity>(); Amount<MyQuantity> amount = new Amount<>();
String json = gson.toJson(amount); String json = gson.toJson(amount);
assertTrue(json.contains("value")); assertTrue(json.contains("value"));
assertTrue(json.contains("30")); assertTrue(json.contains("30"));

View File

@ -50,7 +50,7 @@ public class PrettyPrintingTest extends TestCase {
public void testPrettyPrintList() { public void testPrettyPrintList() {
BagOfPrimitives b = new BagOfPrimitives(); BagOfPrimitives b = new BagOfPrimitives();
List<BagOfPrimitives> listOfB = new LinkedList<BagOfPrimitives>(); List<BagOfPrimitives> listOfB = new LinkedList<>();
for (int i = 0; i < 15; ++i) { for (int i = 0; i < 15; ++i) {
listOfB.add(b); listOfB.add(b);
} }
@ -88,7 +88,7 @@ public class PrettyPrintingTest extends TestCase {
} }
public void testMap() { public void testMap() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>(); Map<String, Integer> map = new LinkedHashMap<>();
map.put("abc", 1); map.put("abc", 1);
map.put("def", 5); map.put("def", 5);
String json = gson.toJson(map); String json = gson.toJson(map);
@ -98,7 +98,7 @@ public class PrettyPrintingTest extends TestCase {
// In response to bug 153 // In response to bug 153
public void testEmptyMapField() { public void testEmptyMapField() {
ClassWithMap obj = new ClassWithMap(); ClassWithMap obj = new ClassWithMap();
obj.map = new LinkedHashMap<String, Integer>(); obj.map = new LinkedHashMap<>();
String json = gson.toJson(obj); String json = gson.toJson(obj);
assertTrue(json.contains("{\n \"map\": {},\n \"value\": 2\n}")); assertTrue(json.contains("{\n \"map\": {},\n \"value\": 2\n}"));
} }

View File

@ -51,7 +51,7 @@ public class RawSerializationTest extends TestCase {
} }
public void testParameterizedObject() { public void testParameterizedObject() {
Bar<Foo> bar = new Bar<Foo>(new Foo(1)); Bar<Foo> bar = new Bar<>(new Foo(1));
String expectedJson = "{\"t\":{\"b\":1}}"; String expectedJson = "{\"t\":{\"b\":1}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);
@ -62,7 +62,7 @@ public class RawSerializationTest extends TestCase {
} }
public void testTwoLevelParameterizedObject() { public void testTwoLevelParameterizedObject() {
Bar<Bar<Foo>> bar = new Bar<Bar<Foo>>(new Bar<Foo>(new Foo(1))); Bar<Bar<Foo>> bar = new Bar<>(new Bar<>(new Foo(1)));
String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}"; String expectedJson = "{\"t\":{\"t\":{\"b\":1}}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);
@ -73,7 +73,7 @@ public class RawSerializationTest extends TestCase {
} }
public void testThreeLevelParameterizedObject() { public void testThreeLevelParameterizedObject() {
Bar<Bar<Bar<Foo>>> bar = new Bar<Bar<Bar<Foo>>>(new Bar<Bar<Foo>>(new Bar<Foo>(new Foo(1)))); Bar<Bar<Bar<Foo>>> bar = new Bar<>(new Bar<>(new Bar<>(new Foo(1))));
String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}"; String expectedJson = "{\"t\":{\"t\":{\"t\":{\"b\":1}}}}";
// Ensure that serialization works without specifying the type explicitly // Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar); String json = gson.toJson(bar);

View File

@ -89,8 +89,8 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
static class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { static class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType; private final Class<?> baseType;
private final String typeFieldName; private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
protected RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName) { protected RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName) {
if (typeFieldName == null || baseType == null) { if (typeFieldName == null || baseType == null) {
@ -105,7 +105,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
* typeFieldName} as the type field name. Type field names are case sensitive. * typeFieldName} as the type field name. Type field names are case sensitive.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName); return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName);
} }
/** /**
@ -113,7 +113,7 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
* the type field name. * the type field name.
*/ */
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
return new RuntimeTypeAdapterFactory<T>(baseType, "type"); return new RuntimeTypeAdapterFactory<>(baseType, "type");
} }
/** /**
@ -151,10 +151,8 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
return null; return null;
} }
final Map<String, TypeAdapter<?>> labelToDelegate final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
= new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
= new LinkedHashMap<Class<?>, TypeAdapter<?>>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate); labelToDelegate.put(entry.getKey(), delegate);

View File

@ -112,14 +112,14 @@ public final class StreamingTypeAdaptersTest extends TestCase {
} }
public void testSerializeMap() { public void testSerializeMap() {
Map<String, Double> map = new LinkedHashMap<String, Double>(); Map<String, Double> map = new LinkedHashMap<>();
map.put("a", 5.0); map.put("a", 5.0);
map.put("b", 10.0); map.put("b", 10.0);
assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\'')); assertEquals("{'a':5.0,'b':10.0}", mapAdapter.toJson(map).replace('"', '\''));
} }
public void testDeserializeMap() throws IOException { public void testDeserializeMap() throws IOException {
Map<String, Double> map = new LinkedHashMap<String, Double>(); Map<String, Double> map = new LinkedHashMap<>();
map.put("a", 5.0); map.put("a", 5.0);
map.put("b", 10.0); map.put("b", 10.0);
assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"'))); assertEquals(map, mapAdapter.fromJson("{'a':5.0,'b':10.0}".replace('\'', '\"')));
@ -163,7 +163,7 @@ public final class StreamingTypeAdaptersTest extends TestCase {
Person.class, typeAdapter).create(); Person.class, typeAdapter).create();
Truck truck = new Truck(); Truck truck = new Truck();
truck.horsePower = 1.0D; truck.horsePower = 1.0D;
truck.passengers = new ArrayList<Person>(); truck.passengers = new ArrayList<>();
truck.passengers.add(null); truck.passengers.add(null);
truck.passengers.add(new Person("jesse", 30)); truck.passengers.add(new Person("jesse", 30));
try { try {

View File

@ -95,7 +95,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) .setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create(); .create();
List<Object> expected = new LinkedList<Object>(); List<Object> expected = new LinkedList<>();
expected.add(null); expected.add(null);
expected.add(10L); expected.add(10L);
expected.add(10.0); expected.add(10.0);

View File

@ -39,14 +39,14 @@ import com.google.gson.reflect.TypeToken;
* Collection of functional tests for DOM tree based type adapters. * Collection of functional tests for DOM tree based type adapters.
*/ */
public class TreeTypeAdaptersTest extends TestCase { public class TreeTypeAdaptersTest extends TestCase {
private static final Id<Student> STUDENT1_ID = new Id<Student>("5", Student.class); private static final Id<Student> STUDENT1_ID = new Id<>("5", Student.class);
private static final Id<Student> STUDENT2_ID = new Id<Student>("6", Student.class); private static final Id<Student> STUDENT2_ID = new Id<>("6", Student.class);
private static final Student STUDENT1 = new Student(STUDENT1_ID, "first"); private static final Student STUDENT1 = new Student(STUDENT1_ID, "first");
private static final Student STUDENT2 = new Student(STUDENT2_ID, "second"); private static final Student STUDENT2 = new Student(STUDENT2_ID, "second");
private static final Type TYPE_COURSE_HISTORY = private static final Type TYPE_COURSE_HISTORY =
new TypeToken<Course<HistoryCourse>>(){}.getType(); new TypeToken<Course<HistoryCourse>>(){}.getType();
private static final Id<Course<HistoryCourse>> COURSE_ID = private static final Id<Course<HistoryCourse>> COURSE_ID =
new Id<Course<HistoryCourse>>("10", TYPE_COURSE_HISTORY); new Id<>("10", TYPE_COURSE_HISTORY);
private Gson gson; private Gson gson;
private Course<HistoryCourse> course; private Course<HistoryCourse> course;
@ -56,7 +56,7 @@ public class TreeTypeAdaptersTest extends TestCase {
gson = new GsonBuilder() gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTreeTypeAdapter()) .registerTypeAdapter(Id.class, new IdTreeTypeAdapter())
.create(); .create();
course = new Course<HistoryCourse>(COURSE_ID, 4, course = new Course<>(COURSE_ID, 4,
new Assignment<HistoryCourse>(null, null), Arrays.asList(STUDENT1, STUDENT2)); new Assignment<HistoryCourse>(null, null), Arrays.asList(STUDENT1, STUDENT2));
} }

View File

@ -38,7 +38,7 @@ public class TypeVariableTest extends TestCase {
public void testAdvancedTypeVariables() throws Exception { public void testAdvancedTypeVariables() throws Exception {
Gson gson = new Gson(); Gson gson = new Gson();
Bar bar1 = new Bar("someString", 1, true); Bar bar1 = new Bar("someString", 1, true);
ArrayList<Integer> arrayList = new ArrayList<Integer>(); ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1); arrayList.add(1);
arrayList.add(2); arrayList.add(2);
arrayList.add(3); arrayList.add(3);
@ -52,7 +52,7 @@ public class TypeVariableTest extends TestCase {
public void testTypeVariablesViaTypeParameter() throws Exception { public void testTypeVariablesViaTypeParameter() throws Exception {
Gson gson = new Gson(); Gson gson = new Gson();
Foo<String, Integer> original = new Foo<String, Integer>("e", 5, false); Foo<String, Integer> original = new Foo<>("e", 5, false);
original.map.put("f", Arrays.asList(6, 7)); original.map.put("f", Arrays.asList(6, 7));
Type type = new TypeToken<Foo<String, Integer>>() {}.getType(); Type type = new TypeToken<Foo<String, Integer>>() {}.getType();
String json = gson.toJson(original, type); String json = gson.toJson(original, type);
@ -103,7 +103,7 @@ public class TypeVariableTest extends TestCase {
public static class Foo<S, T> extends Red<Boolean> { public static class Foo<S, T> extends Red<Boolean> {
private S someSField; private S someSField;
private T someTField; private T someTField;
public final Map<S, List<T>> map = new HashMap<S, List<T>>(); public final Map<S, List<T>> map = new HashMap<>();
public Foo() {} public Foo() {}

View File

@ -35,7 +35,7 @@ import com.google.gson.common.MoreAsserts;
public final class LinkedTreeMapTest extends TestCase { public final class LinkedTreeMapTest extends TestCase {
public void testIterationOrder() { public void testIterationOrder() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
map.put("c", "cola"); map.put("c", "cola");
map.put("b", "bbq"); map.put("b", "bbq");
@ -44,7 +44,7 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testRemoveRootDoesNotDoubleUnlink() { public void testRemoveRootDoesNotDoubleUnlink() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
map.put("c", "cola"); map.put("c", "cola");
map.put("b", "bbq"); map.put("b", "bbq");
@ -57,7 +57,7 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testPutNullKeyFails() { public void testPutNullKeyFails() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
try { try {
map.put(null, "android"); map.put(null, "android");
fail(); fail();
@ -66,7 +66,7 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testPutNonComparableKeyFails() { public void testPutNonComparableKeyFails() {
LinkedTreeMap<Object, String> map = new LinkedTreeMap<Object, String>(); LinkedTreeMap<Object, String> map = new LinkedTreeMap<>();
try { try {
map.put(new Object(), "android"); map.put(new Object(), "android");
fail(); fail();
@ -74,19 +74,19 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testContainsNonComparableKeyReturnsFalse() { public void testContainsNonComparableKeyReturnsFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
assertFalse(map.containsKey(new Object())); assertFalse(map.containsKey(new Object()));
} }
public void testContainsNullKeyIsAlwaysFalse() { public void testContainsNullKeyIsAlwaysFalse() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
assertFalse(map.containsKey(null)); assertFalse(map.containsKey(null));
} }
public void testPutOverrides() throws Exception { public void testPutOverrides() throws Exception {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
assertNull(map.put("d", "donut")); assertNull(map.put("d", "donut"));
assertNull(map.put("e", "eclair")); assertNull(map.put("e", "eclair"));
assertNull(map.put("f", "froyo")); assertNull(map.put("f", "froyo"));
@ -98,7 +98,7 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testEmptyStringValues() { public void testEmptyStringValues() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", ""); map.put("a", "");
assertTrue(map.containsKey("a")); assertTrue(map.containsKey("a"));
assertEquals("", map.get("a")); assertEquals("", map.get("a"));
@ -106,7 +106,7 @@ public final class LinkedTreeMapTest extends TestCase {
public void testLargeSetOfRandomKeys() throws Exception { public void testLargeSetOfRandomKeys() throws Exception {
Random random = new Random(1367593214724L); Random random = new Random(1367593214724L);
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
String[] keys = new String[1000]; String[] keys = new String[1000];
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
keys[i] = Integer.toString(Math.abs(random.nextInt()), 36) + "-" + i; keys[i] = Integer.toString(Math.abs(random.nextInt()), 36) + "-" + i;
@ -121,7 +121,7 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testClear() { public void testClear() {
LinkedTreeMap<String, String> map = new LinkedTreeMap<String, String>(); LinkedTreeMap<String, String> map = new LinkedTreeMap<>();
map.put("a", "android"); map.put("a", "android");
map.put("c", "cola"); map.put("c", "cola");
map.put("b", "bbq"); map.put("b", "bbq");
@ -131,13 +131,13 @@ public final class LinkedTreeMapTest extends TestCase {
} }
public void testEqualsAndHashCode() throws Exception { public void testEqualsAndHashCode() throws Exception {
LinkedTreeMap<String, Integer> map1 = new LinkedTreeMap<String, Integer>(); LinkedTreeMap<String, Integer> map1 = new LinkedTreeMap<>();
map1.put("A", 1); map1.put("A", 1);
map1.put("B", 2); map1.put("B", 2);
map1.put("C", 3); map1.put("C", 3);
map1.put("D", 4); map1.put("D", 4);
LinkedTreeMap<String, Integer> map2 = new LinkedTreeMap<String, Integer>(); LinkedTreeMap<String, Integer> map2 = new LinkedTreeMap<>();
map2.put("C", 3); map2.put("C", 3);
map2.put("B", 2); map2.put("B", 2);
map2.put("D", 4); map2.put("D", 4);
@ -149,7 +149,7 @@ public final class LinkedTreeMapTest extends TestCase {
public void testJavaSerialization() throws IOException, ClassNotFoundException { public void testJavaSerialization() throws IOException, ClassNotFoundException {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out); ObjectOutputStream objOut = new ObjectOutputStream(out);
Map<String, Integer> map = new LinkedTreeMap<String, Integer>(); Map<String, Integer> map = new LinkedTreeMap<>();
map.put("a", 1); map.put("a", 1);
objOut.writeObject(map); objOut.writeObject(map);
objOut.close(); objOut.close();
@ -162,7 +162,7 @@ public final class LinkedTreeMapTest extends TestCase {
@SafeVarargs @SafeVarargs
private final <T> void assertIterationOrder(Iterable<T> actual, T... expected) { private final <T> void assertIterationOrder(Iterable<T> actual, T... expected) {
ArrayList<T> actualList = new ArrayList<T>(); ArrayList<T> actualList = new ArrayList<>();
for (T t : actual) { for (T t : actual) {
actualList.add(t); actualList.add(t);
} }

View File

@ -113,7 +113,7 @@ public class PerformanceTest extends TestCase {
*/ */
public void disabled_testLargeCollectionSerialization() { public void disabled_testLargeCollectionSerialization() {
int count = 1400000; int count = 1400000;
List<CollectionEntry> list = new ArrayList<CollectionEntry>(count); List<CollectionEntry> list = new ArrayList<>(count);
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
list.add(new CollectionEntry("name"+i,"value"+i)); list.add(new CollectionEntry("name"+i,"value"+i));
} }
@ -219,7 +219,7 @@ public class PerformanceTest extends TestCase {
} }
public void disable_testLargeObjectSerializationAndDeserialization() { public void disable_testLargeObjectSerializationAndDeserialization() {
Map<String, Long> largeObject = new HashMap<String, Long>(); Map<String, Long> largeObject = new HashMap<>();
for (long l = 0; l < 100000; l++) { for (long l = 0; l < 100000; l++) {
largeObject.put("field" + l, l); largeObject.put("field" + l, l);
} }
@ -265,7 +265,7 @@ public class PerformanceTest extends TestCase {
} }
public void disabled_testLargeGsonMapRoundTrip() throws Exception { public void disabled_testLargeGsonMapRoundTrip() throws Exception {
Map<Long, Long> original = new HashMap<Long, Long>(); Map<Long, Long> original = new HashMap<>();
for (long i = 0; i < 1000000; i++) { for (long i = 0; i < 1000000; i++) {
original.put(i, i + 1); original.put(i, i + 1);
} }
@ -298,7 +298,7 @@ public class PerformanceTest extends TestCase {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static final class ClassWithList { private static final class ClassWithList {
final String field; final String field;
final List<ClassWithField> list = new ArrayList<ClassWithField>(COLLECTION_SIZE); final List<ClassWithField> list = new ArrayList<>(COLLECTION_SIZE);
ClassWithList() { ClassWithList() {
this(null); this(null);
} }
@ -323,7 +323,7 @@ public class PerformanceTest extends TestCase {
@Expose @Expose
final String field; final String field;
@Expose @Expose
final List<ClassWithExposedField> list = new ArrayList<ClassWithExposedField>(COLLECTION_SIZE); final List<ClassWithExposedField> list = new ArrayList<>(COLLECTION_SIZE);
ClassWithListOfObjects() { ClassWithListOfObjects() {
this(null); this(null);
} }

View File

@ -46,7 +46,7 @@ public class JsonAdapterNullSafeTest extends TestCase {
static final class JsonAdapterFactory implements TypeAdapterFactory { static final class JsonAdapterFactory implements TypeAdapterFactory {
// The recursiveCall in {@link Device.JsonAdapterFactory} is the source of this bug // The recursiveCall in {@link Device.JsonAdapterFactory} is the source of this bug
// because we use it to return a null type adapter on a recursive call. // because we use it to return a null type adapter on a recursive call.
private static final ThreadLocal<Boolean> recursiveCall = new ThreadLocal<Boolean>(); private static final ThreadLocal<Boolean> recursiveCall = new ThreadLocal<>();
@Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { @Override public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
if (type.getRawType() != Device.class || recursiveCall.get() != null) { if (type.getRawType() != Device.class || recursiveCall.get() != null) {

View File

@ -47,7 +47,7 @@ public class OSGiTest extends TestCase {
} }
private Manifest findManifest(String pkg) throws IOException { private Manifest findManifest(String pkg) throws IOException {
List<URL> urls = new ArrayList<URL>(); List<URL> urls = new ArrayList<>();
for (URL u : Collections.list(getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"))) { for (URL u : Collections.list(getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"))) {
InputStream is = u.openStream(); InputStream is = u.openStream();
Manifest mf = new Manifest(is); Manifest mf = new Manifest(is);

View File

@ -44,7 +44,7 @@ public class CollectionsDeserializationBenchmark {
@BeforeExperiment @BeforeExperiment
void setUp() throws Exception { void setUp() throws Exception {
this.gson = new Gson(); this.gson = new Gson();
List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>(); List<BagOfPrimitives> bags = new ArrayList<>();
for (int i = 0; i < 100; ++i) { for (int i = 0; i < 100; ++i) {
bags.add(new BagOfPrimitives(10L, 1, false, "foo")); bags.add(new BagOfPrimitives(10L, 1, false, "foo"));
} }
@ -68,7 +68,7 @@ public class CollectionsDeserializationBenchmark {
StringReader reader = new StringReader(json); StringReader reader = new StringReader(json);
JsonReader jr = new JsonReader(reader); JsonReader jr = new JsonReader(reader);
jr.beginArray(); jr.beginArray();
List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>(); List<BagOfPrimitives> bags = new ArrayList<>();
while(jr.hasNext()) { while(jr.hasNext()) {
jr.beginObject(); jr.beginObject();
long longValue = 0; long longValue = 0;
@ -106,7 +106,7 @@ public class CollectionsDeserializationBenchmark {
StringReader reader = new StringReader(json); StringReader reader = new StringReader(json);
JsonReader jr = new JsonReader(reader); JsonReader jr = new JsonReader(reader);
jr.beginArray(); jr.beginArray();
List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>(); List<BagOfPrimitives> bags = new ArrayList<>();
while(jr.hasNext()) { while(jr.hasNext()) {
jr.beginObject(); jr.beginObject();
BagOfPrimitives bag = new BagOfPrimitives(); BagOfPrimitives bag = new BagOfPrimitives();

View File

@ -97,8 +97,8 @@ public class ProtoTypeAdapter
private Builder(EnumSerialization enumSerialization, CaseFormat fromFieldNameFormat, private Builder(EnumSerialization enumSerialization, CaseFormat fromFieldNameFormat,
CaseFormat toFieldNameFormat) { CaseFormat toFieldNameFormat) {
this.serializedNameExtensions = new HashSet<Extension<FieldOptions, String>>(); this.serializedNameExtensions = new HashSet<>();
this.serializedEnumValueExtensions = new HashSet<Extension<EnumValueOptions, String>>(); this.serializedEnumValueExtensions = new HashSet<>();
setEnumSerialization(enumSerialization); setEnumSerialization(enumSerialization);
setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat); setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat);
} }
@ -280,7 +280,7 @@ public class ProtoTypeAdapter
if (jsonElement.isJsonArray()) { if (jsonElement.isJsonArray()) {
// Handling array // Handling array
Collection<EnumValueDescriptor> enumCollection = Collection<EnumValueDescriptor> enumCollection =
new ArrayList<EnumValueDescriptor>(jsonElement.getAsJsonArray().size()); new ArrayList<>(jsonElement.getAsJsonArray().size());
for (JsonElement element : jsonElement.getAsJsonArray()) { for (JsonElement element : jsonElement.getAsJsonArray()) {
enumCollection.add( enumCollection.add(
findValueByNameAndExtension(fieldDescriptor.getEnumType(), element)); findValueByNameAndExtension(fieldDescriptor.getEnumType(), element));