Java中Pair类作用与使用
时间: 2024-03-28 07:42:26 浏览: 29
在Java中,Pair类用于存储两个对象,通常用于需要返回两个对象的方法中或者需要将两个对象作为单个对象传递时使用。Pair类是一个泛型类,它可以存储任何类型的对象。
以下是Pair类的定义:
```
public class Pair<T, U> {
private final T first;
private final U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public U getSecond() {
return 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 (!Objects.equals(first, pair.first)) return false;
return Objects.equals(second, pair.second);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
}
```
在上面的代码中,Pair类的构造函数接受两个参数,分别是T类型和U类型的对象,然后分别存储在first和second字段中。Pair类还提供了getFirst()和getSecond()方法,用于获取存储的两个对象。
Pair类还实现了equals()、hashCode()和toString()方法,以便在需要时进行比较和输出。
以下是一个使用Pair的示例:
```
Pair<String, Integer> pair = new Pair<>("hello", 123);
String str = pair.getFirst();
Integer num = pair.getSecond();
System.out.println(str); // 输出 "hello"
System.out.println(num); // 输出 123
```
在上面的示例中,我们创建了一个Pair对象,其中存储了一个字符串和一个整数。然后,我们分别调用了getFirst()和getSecond()方法,获取存储的两个对象。最后,将它们输出到控制台上。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)