001package algs43; 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac Edge.java 005 * Execution: java Edge 006 * 007 * Immutable weighted edge. 008 * 009 *************************************************************************/ 010 011/** 012 * The {@code Edge} class represents a weighted edge in an undirected graph. 013 * <p> 014 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/43mst">Section 4.3</a> of 015 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. 016 */ 017public class Edge implements Comparable<Edge> { 018 019 private final int v; 020 private final int w; 021 private final double weight; 022 023 /** 024 * Create an edge between v and w with given weight. 025 */ 026 public Edge(int v, int w, double weight) { 027 this.v = v; 028 this.w = w; 029 this.weight = weight; 030 } 031 032 /** 033 * Return the weight of this edge. 034 */ 035 public double weight() { 036 return weight; 037 } 038 039 /** 040 * Return either endpoint of this edge. 041 */ 042 public int either() { 043 return v; 044 } 045 046 /** 047 * Return the endpoint of this edge that is different from the given vertex 048 * (unless a self-loop). 049 */ 050 public int other(int vertex) { 051 if (vertex == v) return w; 052 else if (vertex == w) return v; 053 else throw new Error("Illegal endpoint"); 054 } 055 056 /** 057 * Compare edges by weight. 058 */ 059 public int compareTo(Edge that) { 060 if (this.weight() < that.weight()) return -1; 061 else if (this.weight() > that.weight()) return +1; 062 else return 0; 063 } 064 065 066 /** 067 * Return a string representation of this edge. 068 */ 069 public String toString() { 070 return String.format("%d--%d %.2f", v, w, weight); 071 } 072 073 074 /** 075 * Test client. 076 */ 077 public static void main(String[] args) { 078 Edge e = new Edge(12, 23, 3.14); 079 StdOut.println(e); 080 } 081}