001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.osm; 003 004/** 005 * A segment consisting of 2 consecutive nodes out of a way. 006 */ 007public final class WaySegment extends IWaySegment<Node, Way> { 008 009 /** 010 * Constructs a new {@code IWaySegment}. 011 * 012 * @param way The way 013 * @param i The node lower index 014 * @throws IllegalArgumentException in case of invalid index 015 */ 016 public WaySegment(Way way, int i) { 017 super(way, i); 018 } 019 020 /** 021 * Determines and returns the way segment for the given way and node pair. You should prefer 022 * {@link IWaySegment#forNodePair(IWay, INode, INode)} whenever possible. 023 * 024 * @param way way 025 * @param first first node 026 * @param second second node 027 * @return way segment 028 * @throws IllegalArgumentException if the node pair is not part of way 029 */ 030 public static WaySegment forNodePair(Way way, Node first, Node second) { 031 int endIndex = way.getNodesCount() - 1; 032 while (endIndex > 0) { 033 final int indexOfFirst = way.getNodes().subList(0, endIndex).lastIndexOf(first); 034 if (second.equals(way.getNode(indexOfFirst + 1))) { 035 return new WaySegment(way, indexOfFirst); 036 } 037 endIndex--; 038 } 039 throw new IllegalArgumentException("Node pair is not part of way!"); 040 } 041 042 /** 043 * Returns this way segment as complete way. 044 * @return the way segment as {@code Way} 045 */ 046 @Override 047 public Way toWay() { 048 Way w = new Way(); 049 w.addNode(getFirstNode()); 050 w.addNode(getSecondNode()); 051 return w; 052 } 053 054 @Override 055 public String toString() { 056 return "WaySegment [way=" + getWay().getUniqueId() + ", lowerIndex=" + getLowerIndex() + ']'; 057 } 058}