Generic pair class

后端 未结 14 1579
情话喂你
情话喂你 2020-12-01 16:49

Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination.

Provide a generic class Pair for representing pair

相关标签:
14条回答
  • 2020-12-01 17:03

    You can look to implementation of standard Java classes AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry. It is pretty easy to google sources:

    • http://www.docjar.com/html/api/java/util/AbstractMap.java.html
    • http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractMap.java
    0 讨论(0)
  • 2020-12-01 17:04

    I think No. Quote:

    "the class should be parameterised over two types..."

    I think they are expecting in terms of :

    public class Pair<ThingA, ThingB>
    
    0 讨论(0)
  • 2020-12-01 17:04

    Getters are broken

    public thing getFirst() {
      return thing.first;
    }
    
    public thing getSecond() {
      return thing.second;
    }
    

    thing should be replaced with this

    0 讨论(0)
  • 2020-12-01 17:05

    thing is a Type Variable in an unsual notation - we usually use one uppercase latter (like T). Then: a type variable does not have any methods, so your getters won't compile.

    Quick improvement: replace all thing with T

    Quick fix for getters:

    public T getFirst() {
     return first;
    }
    
    public T getSecond() {
     return second;
    }
    

    One requirement was to allow two different types for the pair members. So the class signature should look like:

    public Pair<S,T> {
      private S first;
      private T second;
      //...
    }
    
    0 讨论(0)
  • 2020-12-01 17:07

    I implemented something similar but with static builder and chained setters

    public class Pair<R, L> {
    
    private R left;
    private L right;
    
    public static <K,V> Pair<K, V> of(K k, V v) {
        return new Pair<K,V>(k, v);
    }
    
    public Pair() {}
    
    public Pair(R key, L value) {
        this.left(key);
        this.right(value);
    }
    
    public R left() {
        return left;
    }
    
    public Pair<R, L> left(R key) {
        this.left = key;
        return this;
    }
    
    public L right() {
        return right;
    }
    
    public Pair<R, L> right(L value) {
        this.right = value;
        return this;
    }
    }
    
    0 讨论(0)
  • 2020-12-01 17:11

    Apache Commons Lang has a generic pair implementation

    https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

    0 讨论(0)
提交回复
热议问题