在salesforce Apex中,Map是很常用的数据类型,下面总结几个容易混淆的注意点。
1.Map中的key可以是空字符串或者是null吗?
Map<String, String> mapTest = new Map<String, String>();
mapTest.put('', '123');
mapTest.put(null, '123');
System.debug(mapTest);
答案:可以。空字符串和null都可以作为key。
2.Map中的key区分大小写吗?
Map<String, String> mapTest = new Map<String, String>();
mapTest.put('abc', '123');
mapTest.put('Abc', '456');
System.debug(mapTest);
答案:区分。Abc和abc是不同的。
3.哪些数据类型可以做key。
除了我们熟知的String、Id类型可以做Map的key以外,还有哪些类型可以做key?
1.boolean类型
Map<Boolean, String> mapTest = new Map<Boolean, String>();
mapTest.put(true, '123');
mapTest.put(false, '456');
System.debug(mapTest);
2.Date类型
Map<Date, String> mapTest = new Map<Date, String>();
Date myDate = date.newinstance(2024, 6, 6);
mapTest.put(myDate, '123');
System.debug(mapTest);
3.DateTime类型
Map<DateTime, String> mapTest = new Map<DateTime, String>();
DateTime expected = DateTime.newInstance(2024, 6, 6, 3, 3, 3);
mapTest.put(expected, '123');
System.debug(mapTest);
4.Double类型
Map<Double, String> mapTest = new Map<Double, String>();
mapTest.put(12.5, '123');
System.debug(mapTest);
5.Integer类型
Map<Integer, String> mapTest = new Map<Integer, String>();
mapTest.put(12, '123');
System.debug(mapTest);
6.Long类型
Map<Long, String> mapTest = new Map<Long, String>();
mapTest.put(427199000, '123');
System.debug(mapTest);
7.Time类型
Map<Time, String> mapTest = new Map<Time, String>();
Time myTime = Time.newInstance(18, 30, 2, 20);
mapTest.put(myTime, '123');
System.debug(mapTest);
8.Map、Set、List、Object都可以。
Map<String, String> a = new Map<String, String>();
a.put('1', '1');
a.put('2', '2');
Map<Map<String, String>, String> mapTestMap = new Map<Map<String, String>, String>();
mapTestMap.put(a,'1');
System.debug(mapTestMap);
Set<String> set1 = new Set<String>();
set1.add('a');
Map<Set<String>, String> mapTestSet = new Map<Set<String>, String>();
mapTestSet.put(set1, 'a');
System.debug(mapTestSet);
List<String> list1 = new List<String>();
list1.add('a');
Map<List<String>, String> mapTestList = new Map<List<String>, String>();
mapTestList.put(list1, 'a');
System.debug(mapTestList);
Account acc = [SELECT Id, Name FROM Account LIMIT 1];
Map<Account, String> mapTestObject = new Map<Account, String>();
mapTestObject.put(acc, '1');
System.debug(mapTestObject);
貌似所有数据类型都可以做map的key。。。