Integer2 != Integer2 巨坑
最近遇到一个奇怪的问题,存到user中的某个key的数据类型变了
下面这段代码,本来是图方便获取了 map ,然后将list转成string ,然后put回到这个map,然后使用这个map
却不成想,类型也跟着变了。
这就是引用类型使用的风险
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; public class Test { public static void main(String[] args) { User user = new User(); List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); user.setProperty("somekey", list); System.out.println(user.getProperty("somekey").getClass()); // do something stupid Map<String, Object> userProMap = (Map<String, Object>) user.getAllProperties(); userProMap.put("somekey", StringUtils.join((List<String>)user.getProperty("somekey"), ",")); System.out.println(user.getProperty("somekey").getClass()); } } class User { private Map<String, Object> propertyMap; public User() { this.propertyMap = new HashMap<String, Object>(); } public Map<String, Object> getAllProperties() { return this.propertyMap; } public Object getProperty(String key) { return this.propertyMap.get(key); } public void setProperty(String key, Object value) { propertyMap.put(key, value); } }
class java.util.ArrayList class java.lang.String
标签:java,数据类型,somekey,list,引用,propertyMap,public,user From: https://www.cnblogs.com/zno2/p/7053578.html