C# Java HashMap equivalent(C# Java HashMap 等价物)
本文介绍了C# Java HashMap 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 Java 世界进入 C# 世界是否存在等效的 HashMap?如果没有,你会推荐什么?
Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
推荐答案
Dictionary
可能是最接近的.System.Collections.Generic.Dictionary
实现 System.Collections.Generic.IDictionary
接口(类似于 Java 的 Map
接口).
您应该注意的一些显着差异:
Some notable differences that you should be aware of:
- 添加/获取项目
- Java 的 HashMap 具有用于设置/获取项目的
put
和get
方法myMap.put(key, value)
MyObject 值 = myMap.get(key)
- Adding/Getting items
- Java's HashMap has the
put
andget
methods for setting/getting itemsmyMap.put(key, value)
MyObject value = myMap.get(key)
myDictionary[key] = value
MyObject 值 = myDictionary[key]
- Java 的
HashMap
允许空键 如果您尝试添加空键, - .NET 的
Dictionary
会抛出ArgumentNullException
- Java's
HashMap
allows null keys - .NET's
Dictionary
throws anArgumentNullException
if you try to add a null key
- Java 的
HashMap
会将现有值替换为新值. 如果您使用 - .NET 的
Dictionary
将用新值替换现有值.如果您使用Add
方法,它会改为抛出ArgumentException
.
[]
索引,- Java's
HashMap
will replace the existing value with the new one. - .NET's
Dictionary
will replace the existing value with the new one if you use[]
indexing. If you use theAdd
method, it will instead throw anArgumentException
.
- Java 的
HashMap
将返回 null. - .NET 的
Dictionary
将抛出KeyNotFoundException
.您可以使用TryGetValue
方法而不是[]
索引以避免这种情况:MyObject 值 = null;if (!myDictionary.TryGetValue(key, out value)) {/* 键不存在 *
- Java's HashMap has the
- Java 的 HashMap 具有用于设置/获取项目的
织梦狗教程
本文标题为:C# Java HashMap 等价物


基础教程推荐
猜你喜欢
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01