Skip to content

Instantly share code, notes, and snippets.

@HydrangeaPurple
Created July 22, 2021 09:13
Show Gist options
  • Save HydrangeaPurple/8fe20342c8dcc3c3531000ae8c76d9ab to your computer and use it in GitHub Desktop.
Save HydrangeaPurple/8fe20342c8dcc3c3531000ae8c76d9ab to your computer and use it in GitHub Desktop.
强转泛型集合防止警告
package com.exapmle
import java.util.ArrayList;
import java.util.HashMap;
/**
* 强转泛型集合防止警告
*
* @author chengyiqun
* @version V1.0
* @date 2021/7/22 17:10
*/
public class CastCollectionsUtils {
/**
* 防止强转出现警告
*
* @param obj 强转对象
* @param clazz 强转类型内含类型
* @param <T> 泛型
* @return
*/
public static <T> ArrayList<T> castList(Object obj, Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
if (obj instanceof ArrayList<?>) {
for (Object o : (ArrayList<?>) obj) {
result.add(clazz.cast(o));
}
return result;
}
return null;
}
/**
* 防止出现强转警告
*
* @param obj 强转对象
* @param clazz1 HashMap的key
* @param clazz2 value
* @param <K> Key泛型
* @param <V> Value泛型
* @return
*/
public static <K, V> HashMap<K, V> castHashMap(Object obj, Class<K> clazz1, Class<V> clazz2) {
HashMap<K, V> result = new HashMap<K, V>();
if (obj instanceof HashMap<?, ?>) {
for (Object o : ((HashMap<?, ?>) obj).keySet()) {
result.put(clazz1.cast(o), clazz2.cast(((HashMap<?, ?>) obj).get(o)));
}
return result;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment