介绍java中Pair second_Java中的C对<L,R>的等价物是什么?

问题

有没有一个很好的理由为什么Java中没有Pair ?这个C构造的等价物是什么?我宁愿避免重新实现自己。

似乎1.6提供类似的东西(AbstractMap.SimpleEntry ),但这看起来很复杂。

#1 热门回答(359 赞)

在comp.lang.java.help中的一个线程中,Hunter Gratzner给出了一些反对在Java中存在Pair结构的论据。主要论点是类“Pair”没有传达关于两个值之间关系的任何语义(你怎么知道“第一”和“第二”是什么意思?)。

更好的做法是编写一个非常简单的类,就像迈克提出的那样,为每个应用程序编写Pair类。 Map.Entry是一个在其名称中带有其含义的对的示例。

总而言之,在我看来,最好有一个类Position(x,y),一个类Range(开始,结束)和一个类Entry(key,value)而不是一个通用的Pair (第一,第二)它没有告诉我它应该做什么。

#2 热门回答(135 赞)

这是Java。你必须使用描述性的类和字段名称来创建自己的Pair类,并且不要介意通过编写hashCode()/ equals()或一次又一次地实现Comparable来重新发明轮子。

#3 热门回答(99 赞)

HashMap兼容对类:

public class Pair {

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值