C# 난민은 약간의 Java 컬렉션을 찾고 있습니다.
-
06-07-2019 - |
문제
어떤 유형의 컬렉션에 키/값 정보를 저장해야합니다. C#에서는 다음과 같은 사전을 정의합니다.
var entries = new Dictionary<string, int>();
entries.Add("Stop me", 11);
entries.Add("Feed me", 12);
entries.Add("Walk me", 13);
그런 다음 값에 액세스하겠습니다.
int value = entries["Stop me"];
Java에서 어떻게해야합니까? 나는 예제를 보았다 ArrayList
, 그러나 가능하면 제네릭이있는 솔루션을 원합니다.
해결책
당신은 사용하고 싶습니다 Map
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Stop me", 11);
Integer i = m.get("Stop me"); // i == 11
마지막 줄에서 나는 다음과 같이 말할 수있었습니다.
int i = m.get("Stop me");
이는 속기 (Java의 자동 노트 박스 포함) :
int i = m.get("Stop me").intValue()
주어진 키에서 맵에 값이없는 경우 get
보고 null
그리고이 표현은 a NullPointerException
. 그러므로 그것은입니다 언제나 사용하는 것이 좋습니다 박스형 유형 Integer
이 경우
다른 팁
a java.util.Map
. 몇 가지 구현이 있습니다.
HashMap
: o (1) 조회, 키 순서가 유지되지 않습니다.TreeMap
: O (로그 N) 조회, 키 순서를 유지하므로 보장 된 순서로 반복 할 수 있습니다.LinkedHashMap
: o (1) 조회,지도에 추가 된 순서대로 키를 반복합니다.
당신은 다음과 같이 사용합니다.
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Stop me", 11);
map.put("Feed me", 12);
int value = map.get("Stop me");
컬렉션 작업을 추가하기 위해 Google Collections 라이브러리. 훌륭합니다.
당신은 a를 사용합니다 Map
자바에서.
사용할 수 없습니다 int
(또는 기타 원시 유형) 일반 유형 매개 변수로서, 그러나자가 옥싱으로 인해 여전히 동작합니다. 거의 마치 마치 마치 Map<String, int>
대신 a Map<String, Integer>
. (성능에 민감한 코드에서 많은 자서전을하고 싶지는 않습니다.)
Map<String, Integer> entries = new HashMap<String, Integer>();
entries.put("Stop me", 11);
entries.put("Feed me", 12);
entries.put("Walk me", 13);
int value = entries.get("Stop me"); // if you know it exists
// If you're not sure whether the map contains a value, it's better to do:
Integer boxedValue = entries.get("Punch me");
if (boxedValue != null) {
int unboxedValue = boxedValue;
...
}
당신이 같은 것을 찾고있는 것 같습니다 HashMap
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Stop Me", 11);
map.put("Feed Me", 12);
map.put("Walk Me", 13);
Integer x; // little hack
int value = (x = a.get("aaa")) == null? 0 : x;
대안으로 열거를 시도 할 수 있습니다.
enum Action {
STOP(11),
FEED(12),
WALK(13);
private final int value;
private Action(int value) {
this.value = value;
}
public int value() {
return value;
}
public static Action valueOf(int value) {
for (Action action : values()) {
if (action.value == value) {
return action;
}
}
return null; // or a null-object
}
}
테스트:
public void action() {
Action action = Action.valueOf("FEED");
// or Action.FEED for more compile-time safety
int value = action.value();
// instantiating by code
Action walk = Action.valueOf(13);
}
당신은 확실히 원합니다 HashMap
, C#의 Java 버전입니다. Dictionary
.
제휴하지 않습니다 StackOverflow