programing

Java는 한때 Pair 클래스가 있지 않았나요?

minecode 2022. 12. 10. 10:55
반응형

Java는 한때 Pair 클래스가 있지 않았나요?

제가 잘못 기억하고 있나요?아니면 옛날에 Java가 API의 일부로 Pair 클래스를 제공했습니까?

표준 프레임워크에는 쌍이 없지만 "표준"에 상당히 가까운 Apache Commons Lang에는 쌍이 있습니다.

new MutablePair<>(1, "xxx");
new ImmutablePair<>(1, "xxx");

Map.Entry

Java 1.6 이상에서는 키와 값을 페어링하는 인터페이스가2개 실장되어 있습니다.

맵에서 상속되는 SimpleEntry 및 SimpleImmmputableEntry 클래스의 UML 다이어그램.

예를들면

Map.Entry < Month, Boolean > pair = 
    new AbstractMap.SimpleImmutableEntry <>( 
        Month.AUGUST , 
        Boolean.TRUE 
    )
;

pair.toString(): AUGIST=true

사이즈나 오브젝트 컬렉션 등 페어를 저장할 필요가 있을 때 사용합니다.

생산 코드의 이 부분:

public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>>
        getEventTable(RiskClassifier classifier) {
    Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>();
    Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>();
    Map<L3Risk, List<Event>> l3s = new HashMap<>();
    List<Event> events = new ArrayList<>();
    ...
    map.put(l3s, events);
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}

코드는 복잡해 보이지만 지도 대신.개체 배열(크기 2)로 제한한 항목과 유형 검사 손실...

A 쌍 클래스:

public class Pair<K, V> {

    private final K element0;
    private final V element1;

    public static <K, V> Pair<K, V> createPair(K element0, V element1) {
        return new Pair<K, V>(element0, element1);
    }

    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();

불변의, 오직 한 쌍!

이 주변에는 많은 구현이 있지만 항상 뭔가가 누락되어 있습니다. Override of equal and hash method입니다.

이 클래스의 보다 완전한 버전을 다음에 나타냅니다.

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair<F, S> {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}

이게 도움이 될 거야

「」 「」Pair에는 특별한 에 '수업할 때'가 도 있어요.그리고 당신은 그것이 필요할 수 있습니다.Tripplet범용 Java를 포함하지 .Pair 않은)합니다.Point(x,y),Range(start, end) ★★★★★★★★★★★★★★★★★」Map.Entry(key, value).

아니요, 하지만 여러요청했어요.

많은 서드파티 라이브러리가 Pair 버전을 가지고 있지만 Java에는 이러한 클래스가 없습니다.가장 가까운 것은 내부 인터페이스 java.util입니다.Map.Entry: 불변의 키 속성 및 변경 가능한 값 속성을 표시합니다.

아니요, JavaFX가 가지고 있습니다.

Cf. Stack Overflow: Java Pair 클래스 구현

이상해 보이긴 해요.이 스레드는 예전에 본 적이 있다고 생각했지만 자바독에서는 찾을 수 없었습니다.

특화된 클래스를 사용하는 것에 대한 Java 개발자의 요점을 알 수 있습니다.또, 범용 페어 클래스의 존재는 개발자를 게으르게 할 수 있습니다(생각을 게을리 할 수 있습니다.

하지만, 제 경험상, 여러분이 실제로 모델링하고 있는 것은 단지 두 가지일 뿐이고, 두 개의 반쪽 사이의 관계에 대해 의미 있는 이름을 생각해 내는 것이 실제로 그것을 계속하는 것보다 더 고통스러울 때가 있습니다.그래서 대신 우리는 실질적으로 보일러 플레이트 코드의 'bespoke' 클래스를 만들어야 합니다. 아마도 'Pair'라고 불릴 것입니다.

이것은 미끄러운 경사면이 될 수 있지만, 페어 클래스와 트리플렛 클래스는 사용 사례의 대부분을 커버합니다.

(키와 값의 쌍이 아닌) 2개의 범용 데이터를 함께 보관하고 싶은 경우, (키라고 불리는) 위의 솔루션은 처음부터 변경할 수 없습니다(Apache Commons Lang의 쌍에서도 Abstract Map에서도 변경할 수 없습니다.심플 엔트리)나름의 이유가 있지만 두 가지 컴포넌트를 모두 변경해야 할 수도 있습니다.다음은 두 요소를 모두 설정할 수 있는 Pair 클래스입니다.

public class Pair<First, Second> {
    private First first;
    private Second second;

    public Pair(First first, Second second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(First first) {
        this.first = first;
    }

    public void setSecond(Second second) {
        this.second = second;
    }

    public First getFirst() {
        return first;
    }

    public Second getSecond() {
        return second;
    }

    public void set(First first, Second second) {
        setFirst(first);
        setSecond(second);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pair pair = (Pair) o;

        if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
        if (second != null ? !second.equals(pair.second) : pair.second != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }
}

언급URL : https://stackoverflow.com/questions/5303539/didnt-java-once-have-a-pair-class

반응형