자바 에서 C++ Pair에 해당하는 것은?
why이 ?Pair<L,R>
자바에서? C 것은 C++ 구조와 같은 것은 무엇인가?나는 차라리 내 자신의 모습을 되짚어 보는 것을 피하고 싶다.
1.6도 비슷한 것을 제공하고 있는 것 같다 (AbstractMap.SimpleEntry<K,V>
() 그러나 이것은 꽤 복잡해 보인다.
에 대한 줄에서, 헌터 그라츠너는 a의 존재에 대해 몇 가지 주장을 한다.Pair
자바로 짓다주된 논거는 수업이다.Pair
두 가치 사이의 관계에 대한 어떤 의미론도 전달하지 않는다("첫"과 "두 번째"가 무엇을 의미하는지 어떻게 아는가?)
더 좋은 관행은 마이크가 제안한 것과 같은 매우 간단한 수업을 당신이 각 애플리케이션별로 작성하는 것이다.Pair
계급의Map.Entry
그 이름에 그 의미를 담고 있는 한 쌍의 예다.
요약하자면, 내 생각에는 수업을 하는 것이 더 낫다고 생각한다.Position(x,y)
, 클래스Range(begin,end)
그리고 학급.Entry(key,value)
일반적이라기보다는Pair(first,second)
그게 뭘 해야 하는지는 아무 것도 말해주지 않아
자바 입니다.서술형 클래스 및 필드 이름을 가진 자신만의 맞춤 페어 클래스를 만들어야 하며, 해시코드()/equals()를 작성하거나 비교가능성을 반복적으로 구현하여 휠을 재창조하는 것은 개의치 않는다.
해시맵 호환 페어 클래스:
public class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
(( this.first == otherPair.first ||
( this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
( this.second == otherPair.second ||
( this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))) );
}
return false;
}
public String toString()
{
return "(" + first + ", " + second + ")";
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}
내가 생각해 낼 수 있는 가장 짧은 한 쌍은 롬복(Lombok)을 이용하여 다음과 같다.
@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
private F first;
private S second;
}
@arturh(비교적성 제외)로부터 얻은 답변의 모든 장점을 가지고 있다.hashCode
equals
toString
그리고 정적인 "정적인" 이기도 하고.
Apache Commons Lang 3.0+에는 다음과 같은 몇 가지 페어 클래스가 있다: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html
Pair를 구현하는 또 다른 방법.
- 공용 불변 필드, 즉 단순한 데이터 구조.
- 비견할 만한.
- 단순 해시 및 등가.
유형을 제공할 필요가 없도록 간단한 공장. 예: Pair.of("Hello", 1);
public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> { public final FIRST first; public final SECOND second; private Pair(FIRST first, SECOND second) { this.first = first; this.second = second; } public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first, SECOND second) { return new Pair<FIRST, SECOND>(first, second); } @Override public int compareTo(Pair<FIRST, SECOND> o) { int cmp = compare(first, o.first); return cmp == 0 ? compare(second, o.second) : cmp; } // todo move this to a helper class. private static int compare(Object o1, Object o2) { return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1 : ((Comparable) o1).compareTo(o2); } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } // todo move this to a helper class. private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair) obj).first) && equal(second, ((Pair) obj).second); } // todo move this to a helper class. private boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
http://www.javatuples.org/index.html은 어떤가? 나는 그것이 매우 유용하다는 것을 알았다.
자바투플은 1가지에서 10가지 요소까지의 튜플 클래스를 제공한다.
Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)
Quartet<A,B,C,D> (4 elements)
Quintet<A,B,C,D,E> (5 elements)
Sextet<A,B,C,D,E,F> (6 elements)
Septet<A,B,C,D,E,F,G> (7 elements)
Octet<A,B,C,D,E,F,G,H> (8 elements)
Ennead<A,B,C,D,E,F,G,H,I> (9 elements)
Decade<A,B,C,D,E,F,G,H,I,J> (10 elements)
안드로이드가 제공한다.Pair
class(http://developer.android.com/reference/android/util/Pair.html), 여기 구현:
public class Pair<F, S> {
public final F first;
public final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equal(p.first, first) && Objects.equal(p.second, second);
}
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
public static <A, B> Pair <A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
}
어디에 쓰느냐에 따라 달라진다.일반적인 이유는 지도에 반복하기 위함입니다. 지도에 반복하여 간단하게 이 작업을 수행(Java 5+):
Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}
가장 큰 문제는 A와 B에서 불변성을 보장할 수 없다는 점일 것이다(유형 매개변수가 불변성을 보장하는 방법 참조).hashCode()
예를 들어, 집합에 삽입된 후 동일한 쌍에 대해 일관되지 않은 결과를 제공할 수 있다(이는 정의되지 않은 동작을 제공할 수 있음, 변이 가능한 필드의 경우 등가 정의 참조).특정 (일반적이지 않은) 페어 클래스의 경우 프로그래머는 A와 B를 불변으로 신중하게 선택하여 불변성을 보장할 수 있다.
어쨌든 @PeterLawrey의 대답(java 1.7)에서 제네릭의 경고를 지우는 것:
public class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
private Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
// TODO : move this to a helper class.
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
// TODO : move this to a helper class.
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
추가/조립은 매우 환영한다:) 특히, 나는 의 사용에 대해 잘 모르겠다.Pair<?, ?>
.
이 구문을 사용하는 이유에 대한 자세한 내용은 개체에서 비교 가능을 구현하는지 확인 및 자세한 설명을 참조하십시오.Java에서 일반 함수를 구현하는 방법?
Good News JavaFX에는 키 값 쌍이 있다.
종속성으로 JavaFX를 추가하고 가져오기javafx.util.Pair
, 그리고 간단히 C++와 같이 사용한다.
Pair <Key, Value>
예)
Pair <Integer, Integer> pr = new Pair<Integer, Integer>()
pr.get(key);// will return corresponding value
내 생각에, Java에는 페어가 없는 이유는 페어에 직접 추가 기능(예: 비교 가능)을 추가하려면 타입을 바인딩해야 하기 때문이다.C++에서는 상관하지 않으며, 한 쌍을 구성하는 유형에는operator <
그pair::operator <
또한 컴파일되지 않을 것이다.
경계 없는 비교 가능의 예:
public class Pair<F, S> implements Comparable<Pair<? extends F, ? extends S>> {
public final F first;
public final S second;
/* ... */
public int compareTo(Pair<? extends F, ? extends S> that) {
int cf = compare(first, that.first);
return cf == 0 ? compare(second, that.second) : cf;
}
//Why null is decided to be less than everything?
private static int compare(Object l, Object r) {
if (l == null) {
return r == null ? 0 : -1;
} else {
return r == null ? 1 : ((Comparable) (l)).compareTo(r);
}
}
}
/* ... */
Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
//Runtime error here instead of compile error!
System.out.println(a.compareTo(b));
형식 인수의 비교 여부에 대한 Compile-time 확인과 비교 가능 예:
public class Pair<
F extends Comparable<? super F>,
S extends Comparable<? super S>
> implements Comparable<Pair<? extends F, ? extends S>> {
public final F first;
public final S second;
/* ... */
public int compareTo(Pair<? extends F, ? extends S> that) {
int cf = compare(first, that.first);
return cf == 0 ? compare(second, that.second) : cf;
}
//Why null is decided to be less than everything?
private static <
T extends Comparable<? super T>
> int compare(T l, T r) {
if (l == null) {
return r == null ? 0 : -1;
} else {
return r == null ? 1 : l.compareTo(r);
}
}
}
/* ... */
//Will not compile because Thread is not Comparable<? super Thread>
Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
System.out.println(a.compareTo(b));
이것은 좋으나, 이번에는 비교가 안 되는 유형을 쌍의 형식 인수로 사용할 수 없다.일부 유틸리티 클래스에서는 Pair에 대한 대조군을 많이 사용할 수 있지만 C++ 사람들은 그것을 얻지 못할 수도 있다.또 다른 방법은 유형 인수의 한계가 다른 유형 계층 구조로 많은 클래스를 작성하는 것이지만, 가능한 범위와 조합이 너무 많다...
Map.엔트리 인터페이스는 c++ 쌍에 꽤 가깝다.추상맵과 같은 구체적인 구현을 보십시오.SimpleEntry 및 ObstractMap.SimpleImableEntry 첫 번째 항목은 getKey()이고 두 번째 항목은 getValue()이다.
자바 언어의 성격에 따르면, 나는 사람들이 실제로 a를 필요로 하지 않는다고 생각한다.Pair
인터페이스는 보통 그들이 필요로 하는 것이다.예를 들면 다음과 같다.
interface Pair<L, R> {
public L getL();
public R getR();
}
그래서 사람들이 두 가지 가치를 반환하고 싶을 때 다음과 같은 일을 할 수 있다.
... //Calcuate the return value
final Integer v1 = result1;
final String v2 = result2;
return new Pair<Integer, String>(){
Integer getL(){ return v1; }
String getR(){ return v2; }
}
이것은 꽤 가벼운 해결책이며, 「a의 의미란 무엇인가」라는 질문에 답한다.Pair<L,R>
은 두 (을 반환하는 " 답은, 이것은 (다른) 타입의 인터페이스 빌드인데, 각각을 반환하는 방법을 가지고 있다.그것에 의미를 더하는 것은 너에게 달려있다.예를 들어 Position을 사용하는 경우 코드에 해당 위치를 표시하려는 경우PositionX
, 그리고PositionY
을 포함하는Integer
, 보충하기 위해Pair<PositionX,PositionY>
. JSR 308을 사용할 수 있는 경우 다음을 사용하십시오.Pair<@PositionX Integer, @PositionY Ingeger>
단순화 시키기 위해서.
편집: 여기서 한 가지 짚고 넘어가야 할 것은 위의 정의가 형식 매개 변수 이름과 메서드 이름과 명시적으로 연관되어 있다는 것이다.라고 주장하는 사람들의 대답이다.Pair
의미 정보의 부족이다.사실, 그 방법은getL
의미는 "유형 매개변수 L의 유형에 해당하는 요소를 내게 달라"는 의미인데, 이는 의미가 있다.
편집: 삶을 더 쉽게 만들 수 있는 간단한 유틸리티 클래스:
class Pairs {
static <L,R> Pair<L,R> makePair(final L l, final R r){
return new Pair<L,R>(){
public L getL() { return l; }
public R getR() { return r; }
};
}
}
사용법:
return Pairs.makePair(new Integer(100), "123");
JavaFX(Java 8과 함께 번들로 제공됨)에는 Pair< A,B > 클래스가 있음
다른 많은 사람들이 이미 언급했듯이, 페어 클래스가 유용한지 아닌지는 실제로 사용 사례에 달려 있다.
나는 개인 도우미 기능에서 당신의 코드를 더 읽기 쉽게 만들고 그것의 보일러 판 코드를 모두 가지고 다른 가치 클래스를 만들 가치가 없다면 페어 클래스를 사용하는 것은 전적으로 합법적이라고 생각한다.
반면 추상화 수준에 따라 두 가지 사물이나 값을 포함하는 클래스의 의미론을 명확하게 문서화해야 한다면, 그에 대한 클래스를 작성해야 한다.일반적으로 데이터가 비즈니스 객체인 경우 그러하다.
항상 그렇듯이, 그것은 숙련된 판단을 필요로 한다.
두 번째 질문은 Apache Commons 라이브러리의 Pair 클래스를 추천한다.이러한 라이브러리는 Java의 확장된 표준 라이브러리로 간주될 수 있다.
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html
또한 비즈니스 객체에 대한 쓰기 가치 클래스를 단순화하는 Apache Commons의 EqualBuilder, HashCodeBuilder 및 ToStringBuilder를 살펴보십시오.
자바프스 유틸리티 클래스를 사용할 수 있고Pair
그것은 c++의 쌍 <>과 같은 목적을 제공한다.https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html
Collections.singletonMap(left, rigth);
또 다른 롬복 구현
import lombok.Value;
@Value(staticConstructor = "of")
public class Pair<F, S> {
private final F first;
private final S second;
}
단순 방식 객체 [] - 넙치 조광 투플로 사용할 수 있음
구문적으로 유사함에도 불구하고 자바와 C++는 패러다임이 매우 다르다.자바처럼 C++를 쓰는 것은 나쁜 C++이고, C++처럼 자바를 쓰는 것은 나쁜 Java이다.
Eclipse와 같은 반성을 기반으로 한 IDE를 사용하면 "pair" 클래스의 필수 기능을 빠르고 간단하게 작성할 수 있다.클래스를 만들고, 두 필드를 정의하고, 다양한 "XX 생성" 메뉴 옵션을 사용하여 몇 초 만에 클래스를 채운다.비교 가능한 인터페이스를 원한다면 "compareTo"를 빨리 입력해야 할 것이다.
C++ 코드 생성기의 별도 선언/정의 옵션들은 그다지 좋지 않기 때문에, 작은 효용 수업을 손으로 쓰는 것이 더 많은 시간을 소비한다.쌍은 템플릿이기 때문에 사용하지 않는 기능에 대해서는 비용을 지불할 필요가 없고, 타이핑된 ef 시설에서는 코드에 의미 있는 타이프 이름을 할당할 수 있기 때문에 "의미론 없음"에 대한 반대가 실제로 성립되지 않는다.
예를 들어, 복잡한 제네릭을 위한 기본 구성 단위가 되기 위해서는 페어가 좋은 것이 될 것이다.
WeakHashMap<Pair<String, String>, String> map = ...
하스켈의 투플레와 꼭 같다.
자바와 같은 프로그래밍 언어의 경우, 대부분의 프로그래머들이 데이터 구조와 같은 쌍을 나타내기 위해 사용하는 대체 데이터 구조는 두 개의 배열이며, 동일한 색인을 통해 데이터에 접근한다.
예: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#Section0080
이것은 이상적인 것이 아니다. 왜냐하면 데이터는 함께 묶여져야 하지만, 또한 꽤 싸다는 것이 밝혀지기 때문이다.또한, 사용 사례에서 좌표 저장을 요구하는 경우 자체적인 데이터 구조를 구축하는 것이 좋다.
내 도서관에 이런 게 있어
public class Pair<First,Second>{.. }
당신은 구글의 AutoValue 라이브러리인 https://github.com/google/auto/tree/master/value을 사용할 수 있다.
매우 작은 추상 클래스를 만들고 @AutoValue로 주석을 달면 주석 프로세서가 값 의미론을 가진 콘크리트 클래스를 생성한다.
사용자의 편의를 위해 여러 등급의 튜플이 있는 라이브러리:
- 자바투플스.1도에서 10도까지의 튜플이 전부다.
- 자바슬랑.0-8도까지의 튜플과 많은 다른 기능적 굿즈.
- JOOλ. 0~16도 튜플과 기타 기능적 굿즈. (소지자, 나는 유지관리자 회사에서 일한다)
- 기능 자바.0-8도까지의 튜플과 많은 다른 기능적 굿즈.
다른 도서관은 적어도 다음이 포함된다고 언급되어 왔다.Pair
터플을 하다
특히, (수락된 답변에서 주창하는 바와 같이) 명목 타이핑이 아닌 구조적인 타이핑을 많이 사용하는 기능 프로그래밍의 맥락에서, 그러한 도서관과 그 튜플은 매우 유용하다.
브라이언 괴츠, 폴 산도즈, 스튜어트 마크스는 디복스 14에서 QA 세션 동안 그 이유를 설명한다.
일단 가치 유형이 도입되면 표준 라이브러리에 일반 쌍 클래스를 갖는 것은 기술적 부채로 변하게 될 것이다.
참고 항목: Java SE 8에는 쌍이나 튜플이 있는가?
나는 모든 쌍 구현이 두 값의 순서에 대한 속성인 이 주위에 흩어져 있다는 것을 알았다.한 쌍을 떠올리면 둘의 순서가 중요하지 않은 두 가지 항목의 조합이 떠오른다.여기 주문되지 않은 쌍을 구현하고hashCode
, 그리고equals
컬렉션에서 원하는 동작을 보장하기 위해 재정의하십시오.복제도 가능하다.
/**
* The class <code>Pair</code> models a container for two objects wherein the
* object order is of no consequence for equality and hashing. An example of
* using Pair would be as the return type for a method that needs to return two
* related objects. Another good use is as entries in a Set or keys in a Map
* when only the unordered combination of two objects is of interest.<p>
* The term "object" as being a one of a Pair can be loosely interpreted. A
* Pair may have one or two <code>null</code> entries as values. Both values
* may also be the same object.<p>
* Mind that the order of the type parameters T and U is of no importance. A
* Pair<T, U> can still return <code>true</code> for method <code>equals</code>
* called with a Pair<U, T> argument.<p>
* Instances of this class are immutable, but the provided values might not be.
* This means the consistency of equality checks and the hash code is only as
* strong as that of the value types.<p>
*/
public class Pair<T, U> implements Cloneable {
/**
* One of the two values, for the declared type T.
*/
private final T object1;
/**
* One of the two values, for the declared type U.
*/
private final U object2;
private final boolean object1Null;
private final boolean object2Null;
private final boolean dualNull;
/**
* Constructs a new <code>Pair<T, U></code> with T object1 and U object2 as
* its values. The order of the arguments is of no consequence. One or both of
* the values may be <code>null</code> and both values may be the same object.
*
* @param object1 T to serve as one value.
* @param object2 U to serve as the other value.
*/
public Pair(T object1, U object2) {
this.object1 = object1;
this.object2 = object2;
object1Null = object1 == null;
object2Null = object2 == null;
dualNull = object1Null && object2Null;
}
/**
* Gets the value of this Pair provided as the first argument in the constructor.
*
* @return a value of this Pair.
*/
public T getObject1() {
return object1;
}
/**
* Gets the value of this Pair provided as the second argument in the constructor.
*
* @return a value of this Pair.
*/
public U getObject2() {
return object2;
}
/**
* Returns a shallow copy of this Pair. The returned Pair is a new instance
* created with the same values as this Pair. The values themselves are not
* cloned.
*
* @return a clone of this Pair.
*/
@Override
public Pair<T, U> clone() {
return new Pair<T, U>(object1, object2);
}
/**
* Indicates whether some other object is "equal" to this one.
* This Pair is considered equal to the object if and only if
* <ul>
* <li>the Object argument is not null,
* <li>the Object argument has a runtime type Pair or a subclass,
* </ul>
* AND
* <ul>
* <li>the Object argument refers to this pair
* <li>OR this pair's values are both null and the other pair's values are both null
* <li>OR this pair has one null value and the other pair has one null value and
* the remaining non-null values of both pairs are equal
* <li>OR both pairs have no null values and have value tuples <v1, v2> of
* this pair and <o1, o2> of the other pair so that at least one of the
* following statements is true:
* <ul>
* <li>v1 equals o1 and v2 equals o2
* <li>v1 equals o2 and v2 equals o1
* </ul>
* </ul>
* In any other case (such as when this pair has two null parts but the other
* only one) this method returns false.<p>
* The type parameters that were used for the other pair are of no importance.
* A Pair<T, U> can return <code>true</code> for equality testing with
* a Pair<T, V> even if V is neither a super- nor subtype of U, should
* the the value equality checks be positive or the U and V type values
* are both <code>null</code>. Type erasure for parameter types at compile
* time means that type checks are delegated to calls of the <code>equals</code>
* methods on the values themselves.
*
* @param obj the reference object with which to compare.
* @return true if the object is a Pair equal to this one.
*/
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(this == obj)
return true;
if(!(obj instanceof Pair<?, ?>))
return false;
final Pair<?, ?> otherPair = (Pair<?, ?>)obj;
if(dualNull)
return otherPair.dualNull;
//After this we're sure at least one part in this is not null
if(otherPair.dualNull)
return false;
//After this we're sure at least one part in obj is not null
if(object1Null) {
if(otherPair.object1Null) //Yes: this and other both have non-null part2
return object2.equals(otherPair.object2);
else if(otherPair.object2Null) //Yes: this has non-null part2, other has non-null part1
return object2.equals(otherPair.object1);
else //Remaining case: other has no non-null parts
return false;
} else if(object2Null) {
if(otherPair.object2Null) //Yes: this and other both have non-null part1
return object1.equals(otherPair.object1);
else if(otherPair.object1Null) //Yes: this has non-null part1, other has non-null part2
return object1.equals(otherPair.object2);
else //Remaining case: other has no non-null parts
return false;
} else {
//Transitive and symmetric requirements of equals will make sure
//checking the following cases are sufficient
if(object1.equals(otherPair.object1))
return object2.equals(otherPair.object2);
else if(object1.equals(otherPair.object2))
return object2.equals(otherPair.object1);
else
return false;
}
}
/**
* Returns a hash code value for the pair. This is calculated as the sum
* of the hash codes for the two values, wherein a value that is <code>null</code>
* contributes 0 to the sum. This implementation adheres to the contract for
* <code>hashCode()</code> as specified for <code>Object()</code>. The returned
* value hash code consistently remain the same for multiple invocations
* during an execution of a Java application, unless at least one of the pair
* values has its hash code changed. That would imply information used for
* equals in the changed value(s) has also changed, which would carry that
* change onto this class' <code>equals</code> implementation.
*
* @return a hash code for this Pair.
*/
@Override
public int hashCode() {
int hashCode = object1Null ? 0 : object1.hashCode();
hashCode += (object2Null ? 0 : object2.hashCode());
return hashCode;
}
}
이 구현은 적절하게 유닛 테스트를 거쳤으며 세트 및 맵에서의 사용이 시도되었다.
공지사항 나는 이것을 공개 도메인에서 공개한다고 주장하지 않는다.이건 내가 방금 어플리케이션에 사용하기 위해 작성한 코드니까, 사용할 거면 직접 복사하는 것을 자제하고 댓글과 이름을 조금 어질러 줘.내 말뜻을 알아들었나?
만약 누군가가 죽어서 사용하기 쉬운 버전을 원한다면, 나는 https://github.com/lfac-pt/Java-Pair에서 내 것을 이용할 수 있게 했다.또한, 개선은 매우 환영 받는답니다!
com.sun.tools.dvac.util.페어는 페어의 간단한 구현이다.그것은 jdk1.7.0_51\lib\tools.jar에서 찾을 수 있다.
org.apache.commons.lang3 이외.터플.페어, 단순한 인터페이스가 아니야
public class Pair<K, V> {
private final K element0;
private final V element1;
public static <K, V> Pair<K, V> createPair(K key, V value) {
return new Pair<K, V>(key, value);
}
public Pair(K element0, V element1) {
this.element0 = element0;
this.element1 = element1;
}
public K getElement0() {
return element0;
}
public V getElement1() {
return element1;
}
}
사용법:
Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();
불변, 오직 한 쌍!
참조URL: https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java
'programing' 카테고리의 다른 글
Vue.js: v-On:event 또는 @event에 매개 변수가 포함된 익명 함수 (0) | 2022.05.25 |
---|---|
전체 vuejs 구성 요소를 클릭하는 방법 (0) | 2022.05.25 |
X타입에프(struct X typedef) vs.X형 구조체? (0) | 2022.05.25 |
RxJava 스케줄러의 사용 사례 (0) | 2022.05.25 |
DevTools를 통해 vuex 상태를 변경할 수 있는가? (0) | 2022.05.25 |