C# Java HashMap 등가물
자바에서 C#로 넘어가는 것은 HashMap에 상당하는 것이 있습니까?그렇지 않다면 무엇을 추천하시겠습니까?
Dictionary 아마 가장 가까울 거예요. System.Collections.Generic.Dictionary(Java와 비슷한) 인터페이스를 구현합니다.Map인터페이스).
유의해야 할 몇 가지 차이점은 다음과 같습니다.
- 항목 추가/가져오기
- Java의 HashMap에는
put그리고.get아이템 설정/취득 방법myMap.put(key, value)MyObject value = myMap.get(key)
- C#의 딕셔너리 사용방법
[]항목 설정/가져오기 위한 인덱싱myDictionary[key] = valueMyObject value = myDictionary[key]
- Java의 HashMap에는
null열쇠들.- 자바어
HashMapnull 키를 허용합니다. - .NET의
Dictionary던지다ArgumentNullExceptionnull 키를 추가하려고 하면
- 자바어
- 중복 키 추가
- 자바어
HashMap는 기존 값을 새 값으로 바꿉니다. - .NET의
Dictionary를 사용하면 기존 값이 새 값으로 바뀝니다.[]색인화.를 사용하는 경우Add방법, 대신, 그것은 그것을 던질 것이다.ArgumentException.
- 자바어
- 존재하지 않는 키를 가져오려고 시도 중입니다.
- 자바어
HashMapnull이 반환됩니다. - .NET의
Dictionary을 던지다KeyNotFoundException. 이 메서드를 사용할 수식을 변경할 수 있습니다.[]인덱스를 사용하여 이를 방지합니다.
MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
- 자바어
Dictionary에는 위의 두 가지 문제에 대처할 수 있는 방법이 있습니다.
"null" 키를 사용할 수 있는 사전이 필요했지만, 네이티브 키가 없는 것 같아서 직접 작성했습니다.사실은 아주 간단해요.사전에서 상속받아 "null" 키 값을 유지하는 개인 필드를 추가한 다음 인덱서를 덮어씁니다.그건 이런 식이다:
public class NullableDictionnary : Dictionary<string, string>
{
string null_value;
public StringDictionary this[string key]
{
get
{
if (key == null)
{
return null_value;
}
return base[key];
}
set
{
if (key == null)
{
null_value = value;
}
else
{
base[key] = value;
}
}
}
}
이것이 미래에 누군가에게 도움이 되기를 바랍니다.
==========
이 형식으로 수정했습니다.
public class NullableDictionnary : Dictionary<string, object>
'코다딕트 알고리즘'의 예를 들어 이해하도록 도와드릴게요
'Dictionary in C#'은 평행 우주의 'Hashmap in Java'다.
일부 구현은 다릅니다.자세한 내용은 다음 예를 참조하십시오.
Java HashMap 선언:
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
C# 딕셔너리 선언:
Dictionary<int, int> Pairs = new Dictionary<int, int>();
위치에서 값 가져오기:
pairs.get(input[i]); // in Java
Pairs[input[i]]; // in C#
위치에서의 값 설정:
pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i]; // in C#
전체 예는 코드딕트의 알고리즘 아래에서 확인할 수 있습니다.
Java에서의 코드 주소 알고리즘:
import java.util.HashMap;
public class ArrayPairSum {
public static void printSumPairs(int[] input, int k)
{
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < input.length; i++)
{
if (pairs.containsKey(input[i]))
System.out.println(input[i] + ", " + pairs.get(input[i]));
else
pairs.put(k - input[i], input[i]);
}
}
public static void main(String[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
printSumPairs(a, 10);
}
}
C#의 코드딕트 알고리즘
using System;
using System.Collections.Generic;
class Program
{
static void checkPairs(int[] input, int k)
{
Dictionary<int, int> Pairs = new Dictionary<int, int>();
for (int i = 0; i < input.Length; i++)
{
if (Pairs.ContainsKey(input[i]))
{
Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
}
else
{
Pairs[k - input[i]] = input[i];
}
}
}
static void Main(string[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
//method : codaddict's algorithm : O(n)
checkPairs(a, 10);
Console.Read();
}
}
해시 테이블 클래스의 MSDN 문서를 참조하십시오.
키의 해시 코드를 기반으로 구성된 키와 값 쌍의 컬렉션을 나타냅니다.
또, 이것은 스레드 세이프가 아닙니다.
사전 사용 - 해시 테이블을 사용하지만 형식이 안전합니다.
또한 다음 Java 코드:
int a = map.get(key);
//continue with your logic
다음과 같이 C#에서 가장 잘 코딩됩니다.
int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}
이렇게 하면 블록 내에서 변수 "a"의 필요 범위를 지정할 수 있으며 나중에 필요할 경우 블록 외부에서 계속 액세스할 수 있습니다.
그 대답은.
사전
내 기능을 봐, 그 간단한 추가는 사전에서 가장 중요한 멤버 기능을 사용해.
목록에 중복 항목이 포함된 경우 이 함수는 false를 반환합니다.
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> mp = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (mp.ContainsKey(items[i]))
{
return true; // has duplicates
}
mp.Add(items[i], true);
}
return false; // no duplicates
}
나는 단지 내 의견을 말하고 싶었다.
@Powerlord 。
null 문자열 대신 null을 사용합니다.
private static Dictionary<string, string> map = new Dictionary<string, string>();
public static void put(string key, string value)
{
if (value == null) value = "null";
map[key] = value;
}
public static string get(string key, string defaultValue)
{
try
{
return map[key];
}
catch (KeyNotFoundException e)
{
return defaultValue;
}
}
public static string get(string key)
{
return get(key, "null");
}
언급URL : https://stackoverflow.com/questions/1273139/c-sharp-java-hashmap-equivalent
'programing' 카테고리의 다른 글
| Vue에서 조건에 따라 확인란을 취소하려면 어떻게 해야 합니까? (0) | 2022.07.27 |
|---|---|
| Ajax 요청 중에 Vue.js가 구성 요소를 사용하지 않도록 설정함 (0) | 2022.07.27 |
| vue: 내부 컴포넌트에 커스텀 속성을 추가하여 "_ob__" 및 getter/setter를 추가하지 않도록 합니다. (0) | 2022.07.27 |
| 현재 실행 중인 메서드의 이름을 가져오는 중 (0) | 2022.07.27 |
| 모바일에서만 클래스 추가 - Vuej 및 부트스트랩 (0) | 2022.07.26 |