📄 edgecomparator.java
字号:
package dk.itu.nulx30.graph;
import java.util.Comparator;
/**
* This small class makes it possible to make a comparison of
* <code>Edge</code>-objects based on a <code>String</code>-parameter given to
* the constructor of this class. The <code>compare()</code>-method uses the
* method <code>getAttribute()</code> of class <code>Edge</code>.<br>
* <br>
* This method uses reflection to extract a field-value based on the
* <code>String</code>-argument.
*
* @author Mikkel Bundgaard
* @author Troels C. Damgaard
* @author Federico Decara
* @author Jacob W. Winther
*/
public class EdgeComparator implements Comparator {
/** the field in class <code>Edge</code> to compare */
private String compareToField;
/** the sort order be descending if true otherwise ascending */
private boolean sortTopFirst;
/**
* the value to return if the first object in the method
* <code>compare(Object, Object)</code> is larger than the second object.
*/
private int largerThanReturn = -1;
/**
* the value to return if the first object in the method
* <code>compare(Object, Object)</code> is smaller than the second object.
*/
private int lessThanReturn = 1;
/**
* Class constructor specifying the field to compare and the sort order.
*
* @param compareToField the field in class <code>Edge</code> to compare.
* @param sortTopFirst if true will the sort order be descending
* otherwise ascending.
*/
public EdgeComparator( String compareToField, boolean sortTopFirst ){
this.compareToField = compareToField;
if (!sortTopFirst) {
largerThanReturn = 1;
lessThanReturn = -1;
}
}
/**
* Compares its two arguments for order. Returns -1, 0, or 1 if sortTopFirst
* is false and the first argument is less than, equal to, or greater than
* the second. Otherwise 1, 0, or -1 is returned when the first argument is
* less than, equal to, or greater than the second.
*
* @param o1 the first object to be compared.
* @param o2 the second object to be compared.
*
* @return -1, 0, or 1 if sortTopFirst is false and the first argument is less
* than, equal to, or greater than the second. Otherwise 1, 0, or -1 is
* returned when the first argument is less than, equal to, or greater than
* the second.
*/
public int compare( Object o1, Object o2 ) {
double thisVal = ( ( Edge ) o1 ).getAttribute( compareToField );
double otherVal = ( ( Edge ) o2 ).getAttribute( compareToField );
return ( thisVal > otherVal ? largerThanReturn :
( thisVal == otherVal ? 0 : lessThanReturn ) );
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -