Salesforce Apex中的Map类型的注意点

在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。。。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值