Java pair类
在C++中,我们有std::pair的实用程序库,如果我们想把一对数值放在一起,它就有很大的用处。我们一直在寻找一个与Java中的对等的类,但直到Java 7才出现了Pair类。JavaFX 2.2有一个javafx.util.Pair类,可以用来存储一对。我们需要使用javafx.util.Pair类提供的参数化构造函数将值存储到Pair中。
注意: 注意<Key, Value>对是在HashMap/TreeMap中使用的。在这里,<Key, Value>只是指一对被存储在一起的值。
javafx.util.pair类所提供的方法
在Java方法中,pair类的语法是。
**pair <键类型,值类型> var_name = new pair<>(key,value) **。
- pair (K key, V value): 创建一个新的配对。
- boolean equals(): 它被用来比较两对对象。它进行深度比较,即根据存储在配对对象中的值(<key, Value>)来进行比较。
例子
pair p1 = new pair(3,4);
pair p2 = new pair(3,4);
pair p3 = new pair(4,4);
System.out.println(p1.equals(p2) + “ ” + p2.equals(p3));
输出
true false
- String toString(): 这个方法将返回该配对的字符串表示。
- K getKey(): 它返回该配对的键。
- V getValue(): 它返回配对的值。
- int hashCode(): 为配对生成一个哈希代码。
访问值: 使用 getKey() 和 getValue() 方法,我们可以访问一个配对对象的值。
1. getKey(): 获得第一个值。
2. getValue(): 获得第二个值。
注意: 这里,<key,value>指的是一对存储在一起的值。它不像Map中使用的<Key, Value>对。
下面是实现。
//Java program to implement in-built pair classes
import javafx.util.Pair;
class GFG {
public static void main(String[] args) {
pair<Integer, String> p = new pair<Integer, String>(10, "Hello Geeks!");
//printing the values of key and value pair separately
System.out.println("The First value is :" + p.getKey());
System.out.println("The Second value is :" + p.getValue());
}
}
让我们来看看下面的问题。
问题描述 :我们得到了n个学生的名字和他们在测验中获得的相应分数。我们需要找到全班分数最高的学生。
注意:你需要在你的机器上安装Java 8,以便运行下面的程序。
/* Java program to find a Pair which has maximum score*/
import java.util.ArrayList;
import javafx.util.Pair;
class Test {
/* This method returns a Pair which hasmaximum score*/
public static Pair<String, Integer>
getMaximum(ArrayList<Pair<String, Integer> > l)
{
// Assign minimum value initially
int max = Integer.MIN_VALUE;
// Pair to store the maximum marks of a
// student with its name
Pair<String, Integer> ans
= new Pair<String, Integer>("", 0);
// Using for each loop to iterate array of
// Pair Objects
for (Pair<String, Integer> temp : l) {
// Get the score of Student
int val = temp.getValue();
// Check if it is greater than the previous
// maximum marks
if (val > max) {
max = val; // update maximum
ans = temp; // update the Pair
}
}
return ans;
}
// Driver method to test above method
public static void main(String[] args)
{
int n = 5; // Number of Students
// Create an Array List
ArrayList<Pair<String, Integer> > l
= new ArrayList<Pair<String, Integer> >();
/* Create pair of name of student with their
corresponding score and insert into the
Arraylist */
l.add(new Pair<String, Integer>("Student A", 90));
l.add(new Pair<String, Integer>("Student B", 54));
l.add(new Pair<String, Integer>("Student C", 99));
l.add(new Pair<String, Integer>("Student D", 88));
l.add(new Pair<String, Integer>("Student E", 89));
// get the Pair which has maximum value
Pair<String, Integer> ans = getMaximum(l);
System.out.println(ans.getKey() + " is top scorer "
+ "with score of "
+ ans.getValue());
}
}
输出
Student C is top scorer with score of 99
注意: 上述程序可能无法在在线IDE中运行,请使用离线编译器。