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() {
List<LineItem> lineItems = new ArrayList<LineItem>();
List<LineItem> lineItems = new ArrayList<>();
lineItems.add(new LineItem("hammer", 1, 12000000, "USD"));
return new Cart(lineItems, "Happy Buyer", "4111-1111-1111-1111");
}

View File

@ -48,7 +48,7 @@ public final class GraphAdapterBuilder {
private final ConstructorConstructor constructorConstructor;
public GraphAdapterBuilder() {
this.instanceCreators = new HashMap<Type, InstanceCreator<?>>();
this.instanceCreators = new HashMap<>();
this.constructorConstructor = new ConstructorConstructor(instanceCreators, true, Collections.<ReflectionAccessFilter>emptyList());
}
public GraphAdapterBuilder addType(Type type) {
@ -80,7 +80,7 @@ public final class GraphAdapterBuilder {
static class Factory implements TypeAdapterFactory, InstanceCreator {
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) {
this.instanceCreators = instanceCreators;
@ -121,7 +121,7 @@ public final class GraphAdapterBuilder {
@SuppressWarnings("unchecked") // graph.map guarantees consistency between value and T
Element<T> element = (Element<T>) graph.map.get(value);
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.queue.add(element);
}
@ -178,7 +178,7 @@ public final class GraphAdapterBuilder {
currentName = name;
}
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();
} else {
@ -242,7 +242,7 @@ public final class GraphAdapterBuilder {
* The queue of elements to write during serialization. Unused during
* 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

View File

@ -19,7 +19,7 @@ public final class InterceptorFactory implements TypeAdapterFactory {
}
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> {

View File

@ -38,7 +38,7 @@ public class PostConstructAdapterFactory implements TypeAdapterFactory {
if (m.isAnnotationPresent(PostConstruct.class)) {
m.setAccessible(true);
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 {
private final Class<?> baseType;
private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>();
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
private final 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.
*/
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.
*/
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.
*/
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 Map<String, TypeAdapter<?>> labelToDelegate
= new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
= new LinkedHashMap<Class<?>, TypeAdapter<?>>();
final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate);

View File

@ -93,9 +93,9 @@ public final class GraphAdapterBuilderTest {
Type listOfListsType = new TypeToken<List<List<?>>>() {}.getType();
Type listOfAnyType = new TypeToken<List<?>>() {}.getType();
List<List<?>> listOfLists = new ArrayList<List<?>>();
List<List<?>> listOfLists = new ArrayList<>();
listOfLists.add(listOfLists);
listOfLists.add(new ArrayList<Object>());
listOfLists.add(new ArrayList<>());
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
@ -187,7 +187,7 @@ public final class GraphAdapterBuilderTest {
static class Company {
final String name;
final List<Employee> employees = new ArrayList<Employee>();
final List<Employee> employees = new ArrayList<>();
Company(String 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.
*/
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 JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory;
@ -237,7 +237,7 @@ public final class Gson {
this.numberToNumberStrategy = numberToNumberStrategy;
this.reflectionFilters = reflectionFilters;
List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();
List<TypeAdapterFactory> factories = new ArrayList<>();
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
@ -453,7 +453,7 @@ public final class Gson {
out.endArray();
}
@Override public AtomicLongArray read(JsonReader in) throws IOException {
List<Long> list = new ArrayList<Long>();
List<Long> list = new ArrayList<>();
in.beginArray();
while (in.hasNext()) {
long value = longAdapter.read(in).longValue();
@ -486,7 +486,7 @@ public final class Gson {
Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
boolean requiresThreadLocalCleanup = false;
if (threadCalls == null) {
threadCalls = new HashMap<TypeToken<?>, FutureTypeAdapter<?>>();
threadCalls = new HashMap<>();
calls.set(threadCalls);
requiresThreadLocalCleanup = true;
}
@ -498,7 +498,7 @@ public final class Gson {
}
try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<T>();
FutureTypeAdapter<T> call = new FutureTypeAdapter<>();
threadCalls.put(type, call);
for (TypeAdapterFactory factory : factories) {

View File

@ -84,11 +84,10 @@ public final class GsonBuilder {
private Excluder excluder = Excluder.DEFAULT;
private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT;
private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
private final Map<Type, InstanceCreator<?>> instanceCreators
= new HashMap<Type, InstanceCreator<?>>();
private final List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();
private final Map<Type, InstanceCreator<?>> instanceCreators = new HashMap<>();
private final List<TypeAdapterFactory> factories = new ArrayList<>();
/** 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 String datePattern = DEFAULT_DATE_PATTERN;
private int dateStyle = DateFormat.DEFAULT;
@ -102,7 +101,7 @@ public final class GsonBuilder {
private boolean useJdkUnsafe = DEFAULT_USE_JDK_UNSAFE;
private ToNumberStrategy objectToNumberStrategy = DEFAULT_OBJECT_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
@ -227,7 +226,7 @@ public final class GsonBuilder {
* .enableComplexMapKeySerialization()
* .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(8, 8), "b");
* System.out.println(gson.toJson(original, type));
@ -254,7 +253,7 @@ public final class GsonBuilder {
* .enableComplexMapKeySerialization()
* .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(8, 8), "b");
* 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
*/
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);
Collections.reverse(factories);
List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories);
List<TypeAdapterFactory> hierarchyFactories = new ArrayList<>(this.hierarchyFactories);
Collections.reverse(hierarchyFactories);
factories.addAll(hierarchyFactories);
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,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient,
serializeSpecialFloatingPointValues, useJdkUnsafe, longSerializationPolicy,
datePattern, dateStyle, timeStyle, new ArrayList<TypeAdapterFactory>(this.factories),
new ArrayList<TypeAdapterFactory>(this.hierarchyFactories), factories,
objectToNumberStrategy, numberToNumberStrategy, new ArrayList<ReflectionAccessFilter>(reflectionFilters));
datePattern, dateStyle, timeStyle, new ArrayList<>(this.factories),
new ArrayList<>(this.hierarchyFactories), factories,
objectToNumberStrategy, numberToNumberStrategy, new ArrayList<>(reflectionFilters));
}
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.
*/
public JsonArray() {
elements = new ArrayList<JsonElement>();
elements = new ArrayList<>();
}
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
*/
public final class JsonObject extends JsonElement {
private final LinkedTreeMap<String, JsonElement> members =
new LinkedTreeMap<String, JsonElement>();
private final LinkedTreeMap<String, JsonElement> members = new LinkedTreeMap<>();
/**
* 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;
* }
*
* final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
* final Map<String, T> lowercaseToConstant = new HashMap<>();
* for (T constant : rawType.getEnumConstants()) {
* lowercaseToConstant.put(toLowercase(constant), constant);
* }

View File

@ -277,25 +277,25 @@ public final class ConstructorConstructor {
if (SortedSet.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new TreeSet<Object>();
return (T) new TreeSet<>();
}
};
} else if (Set.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new LinkedHashSet<Object>();
return (T) new LinkedHashSet<>();
}
};
} else if (Queue.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new ArrayDeque<Object>();
return (T) new ArrayDeque<>();
}
};
} else {
return new ObjectConstructor<T>() {
@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)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new ConcurrentSkipListMap<Object, Object>();
return (T) new ConcurrentSkipListMap<>();
}
};
} else if (ConcurrentMap.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new ConcurrentHashMap<Object, Object>();
return (T) new ConcurrentHashMap<>();
}
};
} else if (SortedMap.class.isAssignableFrom(rawType)) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new TreeMap<Object, Object>();
return (T) new TreeMap<>();
}
};
} else if (type instanceof ParameterizedType && !(String.class.isAssignableFrom(
TypeToken.get(((ParameterizedType) type).getActualTypeArguments()[0]).getRawType()))) {
return new ObjectConstructor<T>() {
@Override public T construct() {
return (T) new LinkedHashMap<Object, Object>();
return (T) new LinkedHashMap<>();
}
};
} else {
return new ObjectConstructor<T>() {
@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) {
Excluder result = clone();
if (serialization) {
result.serializationStrategies = new ArrayList<ExclusionStrategy>(serializationStrategies);
result.serializationStrategies = new ArrayList<>(serializationStrategies);
result.serializationStrategies.add(exclusionStrategy);
}
if (deserialization) {
result.deserializationStrategies
= new ArrayList<ExclusionStrategy>(deserializationStrategies);
result.deserializationStrategies = new ArrayList<>(deserializationStrategies);
result.deserializationStrategies.add(exclusionStrategy);
}
return result;

View File

@ -52,7 +52,7 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
int modCount = 0;
// 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
@ -166,10 +166,10 @@ public final class LinkedTreeMap<K, V> extends AbstractMap<K, V> implements Seri
if (comparator == NATURAL_ORDER && !(key instanceof 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;
} 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
nearest.left = created;
} 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.
*/
private Object writeReplace() throws ObjectStreamException {
return new LinkedHashMap<K, V>(this);
return new LinkedHashMap<>(this);
}
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) {
this.componentTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<E>(context, componentTypeAdapter, componentType);
new TypeAdapterRuntimeTypeWrapper<>(context, componentTypeAdapter, componentType);
this.componentType = componentType;
}
@ -66,7 +66,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
return null;
}
List<E> list = new ArrayList<E>();
List<E> list = new ArrayList<>();
in.beginArray();
while (in.hasNext()) {
E instance = componentTypeAdapter.read(in);

View File

@ -66,7 +66,7 @@ public final class CollectionTypeAdapterFactory implements TypeAdapterFactory {
TypeAdapter<E> elementTypeAdapter,
ObjectConstructor<? extends Collection<E>> constructor) {
this.elementTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<E>(context, elementTypeAdapter, elementType);
new TypeAdapterRuntimeTypeWrapper<>(context, elementTypeAdapter, elementType);
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.
* 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() {
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) {
return createFactory(new DefaultDateTypeAdapter<T>(this, datePattern));
return createFactory(new DefaultDateTypeAdapter<>(this, datePattern));
}
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) {
return createFactory(new DefaultDateTypeAdapter<T>(this, dateStyle, timeStyle));
return createFactory(new DefaultDateTypeAdapter<>(this, dateStyle, timeStyle));
}
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.
* 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) {
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");
/** 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. */
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
* example, consider a map whose keys are points on a grid. The default JSON
* 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(8, 8), "b");
* System.out.println(gson.toJson(original, type));
@ -151,9 +151,9 @@ public final class MapTypeAdapterFactory implements TypeAdapterFactory {
Type valueType, TypeAdapter<V> valueTypeAdapter,
ObjectConstructor<? extends Map<K, V>> constructor) {
this.keyTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<K>(context, keyTypeAdapter, keyType);
new TypeAdapterRuntimeTypeWrapper<>(context, keyTypeAdapter, keyType);
this.valueTypeAdapter =
new TypeAdapterRuntimeTypeWrapper<V>(context, valueTypeAdapter, valueType);
new TypeAdapterRuntimeTypeWrapper<>(context, valueTypeAdapter, valueType);
this.constructor = constructor;
}
@ -212,9 +212,9 @@ public final class MapTypeAdapterFactory implements TypeAdapterFactory {
}
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()) {
JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey());
keys.add(keyElement);

View File

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

View File

@ -90,7 +90,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
return Collections.singletonList(serializedName);
}
List<String> fieldNames = new ArrayList<String>(alternates.length + 1);
List<String> fieldNames = new ArrayList<>(alternates.length + 1);
fieldNames.add(serializedName);
for (String alternate : alternates) {
fieldNames.add(alternate);
@ -113,7 +113,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
boolean blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE;
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) {
@ -174,7 +174,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
}
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()) {
return result;
}

View File

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

View File

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

View File

@ -221,14 +221,14 @@ public class TypeToken<T> {
}
for (Type itype : clazz.getGenericInterfaces()) {
if (isAssignableFrom(itype, to, new HashMap<String, Type>(typeVarMap))) {
if (isAssignableFrom(itype, to, new HashMap<>(typeVarMap))) {
return true;
}
}
// Interfaces didn't work, try the superclass.
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.
*/
public static TypeToken<?> get(Type type) {
return new TypeToken<Object>(type);
return new TypeToken<>(type);
}
/**
* Gets type literal for the given {@code Class} instance.
*/
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}.
*/
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}.
*/
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 {
* List<Message> messages = new ArrayList<Message>();
* List<Message> messages = new ArrayList<>();
*
* reader.beginArray();
* while (reader.hasNext()) {
@ -131,7 +131,7 @@ import java.util.Arrays;
* }
*
* public List<Double> readDoublesArray(JsonReader reader) throws IOException {
* List<Double> doubles = new ArrayList<Double>();
* List<Double> doubles = new ArrayList<>();
*
* reader.beginArray();
* while (reader.hasNext()) {

View File

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

View File

@ -43,7 +43,7 @@ public final class JavaSerializationTest extends TestCase {
Map<String, Integer> serialized = serializedCopy(map);
assertEquals(map, serialized);
// 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 {

View File

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

View File

@ -119,7 +119,7 @@ public class ParameterizedTypeFixtures {
this.instanceOfT = instanceOfT;
}
@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();
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) {
int startValue = (3 * i) + 1;
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 + 1);
arrayOfCollection[i] = tmpList;

View File

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

View File

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

View File

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

View File

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

View File

@ -50,7 +50,7 @@ public class DelegateTypeAdapterTest extends TestCase {
}
public void testDelegateInvoked() {
List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>();
List<BagOfPrimitives> bags = new ArrayList<>();
for (int i = 0; i < 10; ++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() {
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.VALUE2);
String expectedJson = "[\"VALUE1\",\"VALUE2\"]";
@ -133,7 +133,7 @@ public class EnumTest extends TestCase {
}
public void testEnumSubclassAsParameterizedType() {
Collection<Roshambo> list = new ArrayList<Roshambo>();
Collection<Roshambo> list = new ArrayList<>();
list.add(Roshambo.ROCK);
list.add(Roshambo.PAPER);
@ -164,7 +164,7 @@ public class EnumTest extends TestCase {
}
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");
String json = gson.toJson(map);
assertEquals("{\"VALUE1\":\"test\"}", json);

View File

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

View File

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

View File

@ -91,7 +91,7 @@ public class InstanceCreatorTest extends TestCase {
class SubArrayList<T> extends ArrayList<T> {}
InstanceCreator<List<String>> listCreator = new InstanceCreator<List<String>>() {
@Override public List<String> createInstance(Type type) {
return new SubArrayList<String>();
return new SubArrayList<>();
}
};
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(BaseIntegerAdapter.class) Base<Integer> b;
Container(String a, int b) {
this.a = new Base<String>(a);
this.b = new Base<Integer>(b);
this.a = new Base<>(a);
this.b = new Base<>(b);
}
}

View File

@ -34,7 +34,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization()
.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(8, 8), "b");
String json = gson.toJson(original, type);
@ -42,7 +42,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
assertEquals(original, gson.<Map<Point, String>>fromJson(json, type));
// 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("f", false);
assertEquals("{\"t\":true,\"f\":false}",
@ -58,7 +58,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization()
.create();
Map<Number, String> original = new LinkedHashMap<Number, String>();
Map<Number, String> original = new LinkedHashMap<>();
original.put(1.0D, "a");
original.put(1.0F, "b");
try {
@ -88,7 +88,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
.enableComplexMapKeySerialization()
.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(1, 8), "def");
String json = gson.toJson(original, type);
@ -98,7 +98,7 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
public void testMapWithTypeVariableSerialization() {
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));
Type type = new TypeToken<PointWithProperty<Point>>(){}.getType();
String json = gson.toJson(map, type);
@ -136,6 +136,6 @@ public class MapAsArrayTypeAdapterTest extends TestCase {
}
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() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
@ -89,7 +89,7 @@ public class MapTest extends TestCase {
}
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();
String json = gson.toJson(map, typeOfMap);
assertEquals("{}", json);
@ -102,7 +102,7 @@ public class MapTest extends TestCase {
}
public void testMapSerializationWithNullValue() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
Map<String, Integer> map = new LinkedHashMap<>();
map.put("abc", null);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
@ -120,7 +120,7 @@ public class MapTest extends TestCase {
public void testMapSerializationWithNullValueButSerializeNulls() {
gson = new GsonBuilder().serializeNulls().create();
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
Map<String, Integer> map = new LinkedHashMap<>();
map.put("abc", null);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
@ -129,7 +129,7 @@ public class MapTest extends TestCase {
}
public void testMapSerializationWithNullKey() {
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
Map<String, Integer> map = new LinkedHashMap<>();
map.put(null, 123);
Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
@ -151,7 +151,7 @@ public class MapTest extends TestCase {
}
public void testMapSerializationWithIntegerKeys() {
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
Map<Integer, String> map = new LinkedHashMap<>();
map.put(123, "456");
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
@ -252,7 +252,7 @@ public class MapTest extends TestCase {
}
public void testParameterizedMapSubclassSerialization() {
MyParameterizedMap<String, String> map = new MyParameterizedMap<String, String>(10);
MyParameterizedMap<String, String> map = new MyParameterizedMap<>(10);
map.put("a", "b");
Type type = new TypeToken<MyParameterizedMap<String, String>>() {}.getType();
String json = gson.toJson(map, type);
@ -309,7 +309,7 @@ public class MapTest extends TestCase {
}
}).create();
Map<String, Long> src = new LinkedHashMap<String, Long>();
Map<String, Long> src = new LinkedHashMap<>();
src.put("one", 1L);
src.put("two", 2L);
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
*/
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() {
Map<String, ? extends Collection<? extends Integer>> map =
new LinkedHashMap<String, Collection<Integer>>();
Map<String, ? extends Collection<? extends Integer>> map = new LinkedHashMap<>();
map.put("test", null);
Type typeOfMap =
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
*/
public void testMapOfMapSerialization() {
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Map<String, String> nestedMap = new HashMap<String, String>();
Map<String, Map<String, String>> map = new HashMap<>();
Map<String, String> nestedMap = new HashMap<>();
nestedMap.put("1", "1");
nestedMap.put("2", "2");
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
*/
public void testMapWithQuotes() {
Map<String, String> map = new HashMap<String, String>();
Map<String, String> map = new HashMap<>();
map.put("a\"b", "c\"d");
String json = gson.toJson(map);
assertEquals("{\"a\\\"b\":\"c\\\"d\"}", json);
@ -416,7 +415,7 @@ public class MapTest extends TestCase {
* From issue 227.
*/
public void testWriteMapsWithEmptyStringKey() {
Map<String, Boolean> map = new HashMap<String, Boolean>();
Map<String, Boolean> map = new HashMap<>();
map.put("", true);
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
*/
public void testSerializeMaps() {
Map<String, Object> map = new LinkedHashMap<String, Object>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("a", 12);
map.put("b", null);
LinkedHashMap<String, Object> innerMap = new LinkedHashMap<String, Object>();
LinkedHashMap<String, Object> innerMap = new LinkedHashMap<>();
innerMap.put("test", 1);
innerMap.put("TestStringArray", new String[] { "one", "two" });
map.put("c", innerMap);
@ -443,8 +442,8 @@ public class MapTest extends TestCase {
assertEquals("{\"a\":12,\"b\":null,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
new GsonBuilder().serializeNulls().create().toJson(map));
assertEquals("{\n \"a\": 12,\n \"b\": null,\n \"c\": "
+ "{\n \"test\": 1,\n \"TestStringArray\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}",
+ "{\n \"test\": 1,\n \"TestStringArray\": "
+ "[\n \"one\",\n \"two\"\n ]\n }\n}",
new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(map));
assertEquals("{\"a\":12,\"c\":{\"test\":1,\"TestStringArray\":[\"one\",\"two\"]}}",
new GsonBuilder().create().toJson(map));
@ -530,7 +529,7 @@ public class MapTest extends TestCase {
}
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(5, 7), "b");
String json = "{\"2,3\":\"a\",\"5,7\":\"b\"}";
@ -549,7 +548,7 @@ public class MapTest extends TestCase {
public void testStringKeyDeserialization() {
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("5,7", "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType()));
@ -557,7 +556,7 @@ public class MapTest extends TestCase {
public void testNumberKeyDeserialization() {
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(5.7, "b");
assertEquals(map, gson.fromJson(json, new TypeToken<Map<Double, String>>() {}.getType()));
@ -565,7 +564,7 @@ public class MapTest extends TestCase {
public void testBooleanKeyDeserialization() {
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(false, "b");
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) {
Map<K, V> result = new LinkedHashMap<K, V>();
Map<K, V> result = new LinkedHashMap<>();
result.put(key1, value1);
result.put(key2, value2);
return result;
@ -606,7 +605,7 @@ public class MapTest extends TestCase {
public void testMapNamePromotionWithJsonElementReader() {
String json = "{'2.3':'a'}";
Map<Double, String> map = new LinkedHashMap<Double, String>();
Map<Double, String> map = new LinkedHashMap<>();
map.put(2.3, "a");
JsonElement tree = JsonParser.parseString(json);
assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
@ -635,8 +634,8 @@ public class MapTest extends TestCase {
}
static final class MapClass {
private final Map<String, TestTypes.Base> bases = new HashMap<String, TestTypes.Base>();
private final Map<String, TestTypes.Sub> subs = new HashMap<String, TestTypes.Sub>();
private final Map<String, TestTypes.Base> bases = new HashMap<>();
private final Map<String, TestTypes.Sub> subs = new HashMap<>();
public final void addBase(String name, TestTypes.Base value) {
bases.put(name, value);

View File

@ -49,7 +49,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
}
public void testListOfSubclassFields() {
Collection<Base> list = new ArrayList<Base>();
Collection<Base> list = new ArrayList<>();
list.add(new Base(1));
list.add(new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(list, null);
@ -59,7 +59,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
}
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("sub", new Sub(2, 3));
ClassWithContainersOfBaseFields target = new ClassWithContainersOfBaseFields(null, map);
@ -75,7 +75,7 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
*/
public void testParameterizedSubclassFields() {
ClassWithParameterizedBaseFields target = new ClassWithParameterizedBaseFields(
new ParameterizedSub<String>("one", "two"));
new ParameterizedSub<>("one", "two"));
String json = gson.toJson(target);
assertTrue(json.contains("\"t\":\"one\""));
assertFalse(json.contains("\"s\""));
@ -86,9 +86,9 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
* the declared type
*/
public void testListOfParameterizedSubclassFields() {
Collection<ParameterizedBase<String>> list = new ArrayList<ParameterizedBase<String>>();
list.add(new ParameterizedBase<String>("one"));
list.add(new ParameterizedSub<String>("two", "three"));
Collection<ParameterizedBase<String>> list = new ArrayList<>();
list.add(new ParameterizedBase<>("one"));
list.add(new ParameterizedSub<>("two", "three"));
ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(list, null);
String json = gson.toJson(target);
@ -101,9 +101,9 @@ public class MoreSpecificTypeSerializationTest extends TestCase {
* declared type
*/
public void testMapOfParameterizedSubclassFields() {
Map<String, ParameterizedBase<String>> map = new HashMap<String, ParameterizedBase<String>>();
map.put("base", new ParameterizedBase<String>("one"));
map.put("sub", new ParameterizedSub<String>("two", "three"));
Map<String, ParameterizedBase<String>> map = new HashMap<>();
map.put("base", new ParameterizedBase<>("one"));
map.put("sub", new ParameterizedSub<>("two", "three"));
ClassWithContainersOfParameterizedBaseFields target =
new ClassWithContainersOfParameterizedBaseFields(null, map);
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 {
ClassWithTransientFields<Long> target = new ClassWithTransientFields<Long>(1L);
ClassWithTransientFields<Long> target = new ClassWithTransientFields<>(1L);
assertEquals(target.getExpectedJson(), gson.toJson(target));
}
@ -259,7 +259,7 @@ public class ObjectTest extends TestCase {
}
private static class ClassWithCollectionField {
Collection<String> children = new ArrayList<String>();
Collection<String> children = new ArrayList<>();
}
public void testPrimitiveArrayInAnObjectDeserialization() throws Exception {
@ -497,7 +497,7 @@ public class ObjectTest extends TestCase {
}
public class HasObjectMap {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new HashMap<>();
}
static final class Department {
@ -506,7 +506,7 @@ public class ObjectTest extends TestCase {
}
static final class Product {
private List<String> attributes = new ArrayList<String>();
private List<Department> departments = new ArrayList<Department>();
private List<String> attributes = new ArrayList<>();
private List<Department> departments = new ArrayList<>();
}
}

View File

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

View File

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

View File

@ -51,7 +51,7 @@ public class RawSerializationTest extends TestCase {
}
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}}";
// Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar);
@ -62,7 +62,7 @@ public class RawSerializationTest extends TestCase {
}
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}}}";
// Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar);
@ -73,7 +73,7 @@ public class RawSerializationTest extends TestCase {
}
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}}}}";
// Ensure that serialization works without specifying the type explicitly
String json = gson.toJson(bar);

View File

@ -89,8 +89,8 @@ public final class RuntimeTypeAdapterFactoryFunctionalTest extends TestCase {
static class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType;
private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>();
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
protected RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName) {
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.
*/
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.
*/
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;
}
final Map<String, TypeAdapter<?>> labelToDelegate
= new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
= new LinkedHashMap<Class<?>, TypeAdapter<?>>();
final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate);

View File

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

View File

@ -95,7 +95,7 @@ public class ToNumberPolicyFunctionalTest extends TestCase {
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setNumberToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create();
List<Object> expected = new LinkedList<Object>();
List<Object> expected = new LinkedList<>();
expected.add(null);
expected.add(10L);
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.
*/
public class TreeTypeAdaptersTest extends TestCase {
private static final Id<Student> STUDENT1_ID = new Id<Student>("5", Student.class);
private static final Id<Student> STUDENT2_ID = new Id<Student>("6", Student.class);
private static final Id<Student> STUDENT1_ID = new Id<>("5", 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 STUDENT2 = new Student(STUDENT2_ID, "second");
private static final Type TYPE_COURSE_HISTORY =
new TypeToken<Course<HistoryCourse>>(){}.getType();
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 Course<HistoryCourse> course;
@ -56,7 +56,7 @@ public class TreeTypeAdaptersTest extends TestCase {
gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTreeTypeAdapter())
.create();
course = new Course<HistoryCourse>(COURSE_ID, 4,
course = new Course<>(COURSE_ID, 4,
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 {
Gson gson = new Gson();
Bar bar1 = new Bar("someString", 1, true);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
@ -52,7 +52,7 @@ public class TypeVariableTest extends TestCase {
public void testTypeVariablesViaTypeParameter() throws Exception {
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));
Type type = new TypeToken<Foo<String, Integer>>() {}.getType();
String json = gson.toJson(original, type);
@ -103,7 +103,7 @@ public class TypeVariableTest extends TestCase {
public static class Foo<S, T> extends Red<Boolean> {
private S someSField;
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() {}

View File

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

View File

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

View File

@ -46,7 +46,7 @@ public class JsonAdapterNullSafeTest extends TestCase {
static final class JsonAdapterFactory implements TypeAdapterFactory {
// 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.
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) {
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 {
List<URL> urls = new ArrayList<URL>();
List<URL> urls = new ArrayList<>();
for (URL u : Collections.list(getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"))) {
InputStream is = u.openStream();
Manifest mf = new Manifest(is);

View File

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

View File

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