在C++中,我们有 配对 在实用程序库中,如果我们想把一对值保存在一起,它是非常有用的。我们在Java中为pair寻找一个等价的类,但pair类直到Java7才出现。JavaFX2.2具有 javafx。util。一对 类,该类可用于存储一对。我们需要使用 javafx。util。一对 班 注: 请注意,
null
javafx提供的方法。util。结对班
- 配对(K键,V值): 创建一对新的
- 布尔等于() 它用于比较两对对象。它会进行深度比较,也就是说,它基于存储在pair对象中的值(
)进行比较。 例子: 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));
输出: 真假
- 字符串toString(): 此方法将返回该对的字符串表示形式。
- K getKey(): 它返回配对的密钥。
- V getValue(): 它将返回该对的值。
- int hashCode(): 为该对生成哈希代码。
让我们看看下面的问题。 问题陈述: 我们得到了n名学生的名字,以及他们在测验中获得的相应分数。我们需要找到班上得分最高的学生。
注意:为了运行下面的程序,需要在机器上安装Java 8。
/* Java program to find a Pair which has maximum score*/
import
javafx.util.Pair;
import
java.util.ArrayList;
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中运行,请使用脱机编译器。
参考资料: https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html
本文由 希拉格·阿加瓦尔 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END