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