通用对类 [英] Generic pair class

查看:128
本文介绍了通用对类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



提供一个用于表示事物对的泛型类Pair 。这个类应该提供一个构造函数,一个获得这个对的第一个成员的方法,一个获得这个对的第二个成员的方法,一个设置这个对的第一个成员的方法,一个设置这个对的第二个成员的方法。这个类应该为第一个成员和第二个成员两个参数化。



这是这个问题的正确实现吗?

  public class Pair< firstThing,secondThing> {
private firstThing first; //第一个成员
private secondThing第二个; //第二对成员

public Pair(firstThing first,secondThing second){
this.first = first;
this.second = second;
}

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

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

public thing getFirst(){
return this.first;
}

public thing getSecond(){
return this.second;
}
}


解决方案

。我会这样写:

  public class Pair< F,S> {
私人F第一; //第一个成员
私人S秒; //对的第二个成员

public Pair(F first,S second){
this.first = first;
this.second = second;
}

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

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

public F getFirst(){
首先返回;
}

public S getSecond(){
return second;
}
}

编辑:我同意@ karmakaze的评论。代码应该跳过setter并做出第一次和第二次final以保持它不可变。

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 pairs of things. The class should provide a constructor, a method for getting the first member of the pair, a method for getting the second member of the pair, a method for setting the first member of the pair, a method for setting the second member of the pair. The class should be parameterised over two types one for the first member and one for the second member of the pair.

Is this a correct implementation for this question ?

public class Pair<firstThing, secondThing>{
   private firstThing first;//first member of pair
   private secondThing second;//second member of pair

   public Pair(firstThing first, secondThing second){
     this.first = first;
     this.second = second;
   }

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

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

   public thing getFirst() {
     return this.first;
   }

   public thing getSecond() {
     return this.second;
   }
}

解决方案

Almost. I'd write it like this:

public class Pair<F, S> {
    private F first; //first member of pair
    private S second; //second member of pair

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

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

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

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }
}

Edit: I agree with @karmakaze's comment. The code should skip the setters and make first and second final to keep it immutable.

这篇关于通用对类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆