Java - 새 항목 작성 방법(키, 값)
비슷한 항목을 새로 만들고 싶다.Util.Map.Entry
그 구조물을 담을 수 있는key
,value
.
문제는 a를 인스턴스화할 수 없다는 것이다.Map.Entry
인터페이스니까.
지도에 대한 새로운 일반 키/값 객체를 만드는 방법을 아는 사람이 있는가?입장?
있다.하지마Abstract
그 이름의 일부는 당신을 오해하게 한다: 그것은 사실 그것이 아니다.abstract
클래스(그러나 그 최상위 레벨은 다음과 같다.
그 사실 자체가.static
중첩 클래스는 엔클로저가 필요하지 않음을 의미한다.AbstractMap
인스턴스화(instance)를 통해 다음과 같은 것들이 잘 조합된다.
Map.Entry<String,Integer> entry =
new AbstractMap.SimpleEntry<String, Integer>("exmpleString", 42);
다른 대답에서 지적한 바와 같이 구아바에도 편리한 것이 있다.static
사용할 수 있는 공장 방식.
당신은 다음과 같이 말했다:
사용할 수 없다
Map.Entry
분명히 읽기 전용의 대상이기 때문에 새로운 것을 인스턴스화할 수 없다.instanceof
그것은 완전히 정확한 것은 아니다.직접 인스턴스화할 수 없는 이유(즉, 로).new
)은 ~이기 때문이다.
주의사항 및 팁
문서에 언급된 바와 같이,AbstractMap.SimpleEntry
이다@since 1.6
5.0을 고수하고 있다면 그건 불가능할 겁니다.
다음 클래스로 알려진 다른 클래스를 찾으려면implements Map.Entry
사실 당신은 자바독으로 직접 갈 수 있다.Java 6 버전부터
인터페이스 맵.엔트리
알려진 모든 구현 클래스:
불행히도 1.5 버전에는 당신이 사용할 수 있는 알려진 구현 클래스가 나열되어 있지 않기 때문에 당신은 자신의 구현에 집착했을지도 모른다.
Java 9부터, 불변의 항목을 만들 수 있는 새로운 유틸리티 방법이 있다.
여기 간단한 예가 있다.
Entry<String, String> entry = Map.entry("foo", "bar");
불변의 법칙이니 불러라.setValue
을 던질 것이다UnsupportedOperationException
다른 한계는 연재할 수 없다는 사실이고null
키나 값이 금지되어 있기 때문에, 만약 그것이 당신에게 받아들여지지 않는다면, 당신은 또는 대신 사용할 필요가 있을 것이다.
NB: 직접 생성해야 할 경우Map
0에서 최대 10개의 (키, 값) 쌍으로, 대신 형식 방법을 사용할 수 있다.
그냥 구현하면 된다.Map.Entry<K, V>
자체 인터페이스:
import java.util.Map;
final class MyEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public MyEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
}
그런 다음 다음을 사용하십시오.
Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);
System.out.println(entry.getKey());
System.out.println(entry.getValue());
Try Maps.UmableEntry from Guava
이것은 자바 5와 호환될 수 있다는 장점이 있다(과 달리).AbstractMap.SimpleEntry
자바 6이 필요하다.)
추상 맵의 예.SimpleEntry:
import java.util.Map;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
인스턴스화:
ArrayList<Map.Entry<Integer, Integer>> arr =
new ArrayList<Map.Entry<Integer, Integer>>();
행 추가:
arr.add(new AbstractMap.SimpleEntry(2, 3));
arr.add(new AbstractMap.SimpleEntry(20, 30));
arr.add(new AbstractMap.SimpleEntry(2, 4));
행 가져오기:
System.out.println(arr.get(0).getKey());
System.out.println(arr.get(0).getValue());
System.out.println(arr.get(1).getKey());
System.out.println(arr.get(1).getValue());
System.out.println(arr.get(2).getKey());
System.out.println(arr.get(2).getValue());
인쇄 여부:
2
3
20
30
2
4
그것은 그래프 구조의 가장자리를 정의하는 데 좋다.머릿속에 있는 뉴런들 사이에 있는 것 처럼요
실제로 다음과 같이 할 수 있다.Map.Entry<String, String> en= Maps.immutableEntry(key, value);
맵의 설명서를 보면.정적 인터페이스(Map 인터페이스 내부에 정의된 인터페이스)임을 알게 될 항목 a는 Map을 통해 액세스할 수 있다.엔트리) 및 2개의 구현이 있음
알려진 모든 구현 클래스:
추상 지지도.SimpleEntry, OccractMap. 단순불가침입
클래스 추상 맵.SimpleEntry는 다음 두 개의 생성자를 제공한다.
및 및명명명
추상 지지도.SimpleEntry(K 키, V 값)
지정된 키에서 에 대한 매핑을 나타내는 항목 생성
지정 값
추상 지만도.SimpleEntry(지수도).K를 확장하고 V를 확장한다.)
지정된 항목과 동일한 매핑을 나타내는 항목을 작성한다.
사용 사례의 예:
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
public class MyClass {
public static void main(String args[]) {
Map.Entry e = new SimpleEntry<String, String>("Hello","World");
System.out.println(e.getKey()+" "+e.getValue());
}
}
왜Map.Entry
키-값 쌍 같은 것이 그 경우에 적합한 것 같다.
사용하다java.util.AbstractMap.SimpleImmutableEntry
또는java.util.AbstractMap.SimpleEntry
org.apache.commons.lang3.tuple.Pair
를 사용하다java.util.Map.Entry
또한 독립적으로 사용할 수 있다.
또한 다른 사람들이 구아바에 대해 언급했듯이com.google.common.collect.Maps.immutableEntry(K, V)
요령을 터득하다
나는 더 좋아한다.Pair
유창하게Pair.of(L, R)
구문.
나는 항상 사용하는 일반 페어 클래스를 정의했다.훌륭해.보너스로서, 정적 공장법(Pair.create)을 정의함으로써 나는 유형 인수를 절반만 자주 쓰면 된다.
public class Pair<A, B> {
private A component1;
private B component2;
public Pair() {
super();
}
public Pair(A component1, B component2) {
this.component1 = component1;
this.component2 = component2;
}
public A fst() {
return component1;
}
public void setComponent1(A component1) {
this.component1 = component1;
}
public B snd() {
return component2;
}
public void setComponent2(B component2) {
this.component2 = component2;
}
@Override
public String toString() {
return "<" + component1 + "," + component2 + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((component1 == null) ? 0 : component1.hashCode());
result = prime * result
+ ((component2 == null) ? 0 : component2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Pair<?, ?> other = (Pair<?, ?>) obj;
if (component1 == null) {
if (other.component1 != null)
return false;
} else if (!component1.equals(other.component1))
return false;
if (component2 == null) {
if (other.component2 != null)
return false;
} else if (!component2.equals(other.component2))
return false;
return true;
}
public static <A, B> Pair<A, B> create(A component1, B component2) {
return new Pair<A, B>(component1, component2);
}
}
Clojure를 사용하는 경우 다른 옵션을 선택하십시오.
(defn map-entry
[k v]
(clojure.lang.MapEntry/create k v))
참조URL: https://stackoverflow.com/questions/3110547/java-how-to-create-new-entry-key-value
'Programing' 카테고리의 다른 글
장치 드라이버 쓰기를 어떻게 시작해야 하는가? (0) | 2022.04.20 |
---|---|
템플릿이나 프레임워크를 사용하지 않고 Phonegap으로 Vue.js 설정 (0) | 2022.04.20 |
오리지널텍스트 vue, .apk 파일을 얻는 방법? (0) | 2022.04.20 |
_JAVA_OPTIONS, JAVA_의 차이점TOOL_OPTS 및 JAVA_OPTS (0) | 2022.04.20 |
기존 각도 애플리케이션에 vueJS 추가 (0) | 2022.04.20 |