1 11 package org.eclipse.core.internal.databinding.observable.tree; 12 13 import org.eclipse.core.runtime.Assert; 14 15 25 public final class TreePath { 26 27 30 public static final TreePath EMPTY = new TreePath(new Object [0]); 31 32 private Object [] segments; 33 34 private int hash; 35 36 43 public TreePath(Object [] segments) { 44 Assert.isNotNull(segments); 45 for (int i = 0; i < segments.length; i++) { 46 Assert.isNotNull(segments[i]); 47 } 48 this.segments = segments; 49 } 50 51 58 public Object getSegment(int index) { 59 return segments[index]; 60 } 61 62 67 public int getSegmentCount() { 68 return segments.length; 69 } 70 71 76 public Object getFirstSegment() { 77 if (segments.length == 0) { 78 return null; 79 } 80 return segments[0]; 81 } 82 83 88 public Object getLastSegment() { 89 if (segments.length == 0) { 90 return null; 91 } 92 return segments[segments.length - 1]; 93 } 94 95 100 public boolean equals(Object other) { 101 if (!(other instanceof TreePath)) { 102 return false; 103 } 104 TreePath otherPath = (TreePath) other; 105 if (segments.length != otherPath.segments.length) { 106 return false; 107 } 108 for (int i = 0; i < segments.length; i++) { 109 if (!segments[i].equals(otherPath.segments[i])) { 110 return false; 111 } 112 } 113 return true; 114 } 115 116 public int hashCode() { 117 if (hash == 0) { 118 for (int i = 0; i < segments.length; i++) { 119 hash += segments[i].hashCode(); 120 } 121 } 122 return hash; 123 } 124 125 134 public boolean startsWith(TreePath treePath) { 135 int thisSegmentCount = getSegmentCount(); 136 int otherSegmentCount = treePath.getSegmentCount(); 137 if (otherSegmentCount == thisSegmentCount) { 138 return equals(treePath); 139 } 140 if (otherSegmentCount > thisSegmentCount) { 141 return false; 142 } 143 for (int i = 0; i < otherSegmentCount; i++) { 144 Object otherSegment = treePath.getSegment(i); 145 if (!otherSegment.equals(segments[i])) { 146 return false; 147 } 148 } 149 return true; 150 } 151 152 157 public TreePath getParentPath() { 158 int segmentCount = getSegmentCount(); 159 if (segmentCount <= 1) { 160 return null; 161 } 162 Object [] parentSegments = new Object [segmentCount - 1]; 163 System.arraycopy(segments, 0, parentSegments, 0, segmentCount - 1); 164 return new TreePath(parentSegments); 165 } 166 167 172 public TreePath createChildPath(Object newSegment) { 173 int segmentCount = getSegmentCount(); 174 Object [] childSegments = new Object [segmentCount + 1]; 175 if(segmentCount>0) { 176 System.arraycopy(segments, 0, childSegments, 0, segmentCount); 177 } 178 childSegments[segmentCount] = newSegment; 179 return new TreePath(childSegments); 180 } 181 } 182 | Popular Tags |