Java 按字典顺序比较顶点

标签 java

我们正在做一项作业,它比较不同边缘的权重,返回 true 或 false,我只需要有人在这里解释老师的代码

boolean thisTest;

int small = (thisTest = u < v) ? u : v,
big = (thisTest) ? v : u;

有人可以解释一下这里的操作吗?

谢谢

最佳答案

相当于:

if u < v 
   thisTest = true
else 
    thisTest = false

if(thisTest)
  small = u;
else
  small = v;

if(thisTest)
  big = v;
else
  big = u;

如果我们仔细观察:

int small = (thisTest = u < v) ? u : v;

(thisTest = u < v)首先被评估。所以如果 u < v , thisTest = true否则thisTest = false .

所以你有:

boolean thisTest = u < v;
int small = thisTest ? u : v; //ternary operator, if thisTest is true then small = u else small = v
big = thisTest ? v : u; //same reason, if thisTest is true, then big = v else big = u

总而言之,small将包含 u 之间的最小值和vbig将包含最大的。如果u == v , bigsmall将具有相同的值。

您可以了解更多信息here :

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands.

关于Java 按字典顺序比较顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227185/

相关文章:

java - 从不同的类调用方法并保持非静态

java - 在列表上映射通用方法并生成结果列表

java - 有没有办法在 for 循环中链接列表(或 map )?

java - 我们可以在 java 代码终止后将 HashMap 的值保留在内存中吗?

java - Akka 是否有一个 ExecutorCompletionService 等效项,其中 Futures 按其完成时间排队?

java - 扩展@Named @SessionScoped bean

java - Microbreaks - java swing 工具

java - 为什么我不能将 2 个 EJB 注入(inject)到 2 个相互注入(inject)的不同托管 bean 中?

java - 为什么 wait , notify 和 notifyAll 方法都在 Object 类中?

java - MathTransform 在 Android 项目中不起作用 : "The type java.awt.geom.Point2D$Double cannot be resolved."