-2

I'm using some code that I got from an online source for my graph theory portion of a chemical modeling project. I'm trying to make sense of this. What does the first line of code mean in regards to the class's decision of which is one overall? One is the first vertex, two is the second vertex of the class. I'm not well versed in Linear Algebra/Discrete Math, so avoid mathematically intense explanations if possible.

public Edge(Vertex one, Vertex two, int length){
    this.one = (one.getElement().compareTo(two.getElement()) <= 0) ? one : two;
    this.two = (this.one == one) ? two : one;
    this.length = length;
}

Thanks!

PianoFingers
  • 117
  • 2
  • 6
  • 1
    That is the [Conditional Operator `? :`](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25) also known as a [ternary operator](https://en.wikipedia.org/wiki/%3F:). – Elliott Frisch Mar 31 '16 at 01:56

2 Answers2

2

It's poorly written. Two tests where one would do, and almost deliberate obscurity. It's just trying to assign the lesser vertex to one and the other one to two, so as to keep the edges consistently ordered. A clearer version would be:

public Edge(Vertex one, Vertex two, int length)
{
    if (one.getElement().compareTo(two.getElement()) <= 0)
    {
        this.one = one;
        this.two = two;
    }
    else
    {
        this.one = two;
        this.two = one;
    }
    this.length = length;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Too many close-parens in `if` statement. Suggestion (for you and all programmers writing code like this): Add comment like this before `if` statement: `// Assign to fields, but assign vertex with lowest element to field "one"`. – Andreas Mar 31 '16 at 03:03
  • @Andreas I doubt that I would do that, it seems clear enough to me. – user207421 Mar 31 '16 at 04:02
0

Not real sure what you are trying to do here but the first line is using the Comparable interface which, whatever Vertex.getElement() returns, implements. If one's element is "less than or equal" to two's element then this edge's one is set to the given one otherwise it's set to two. The second line then sets this's two accordingly (i.e. if we decided this.one = one then this.two = two otherwise this.one = two and this.two = one).

Jared
  • 940
  • 5
  • 9