List of usage examples for java.lang Comparable compareTo
public int compareTo(T o);
From source file:org.kuali.kra.budget.calculator.QueryList.java
/** * sorts the QueryList by the fieldName in ascending or descending order. * Note: the field Object should be of Comparable type. * @return boolean indicating whether the sort is completed successfully or not. * @param ignoreCase use only when comparing strings. as default implementation uses case sensitive comparison. * @param fieldName field which is used to sort the bean. * @param ascending if true sorting is done in ascending order, * else sorting is done in descending order. *///from www . ja va2 s .c om @SuppressWarnings("rawtypes") public boolean sort(String fieldName, boolean ascending, boolean ignoreCase) { Object current, next; int compareValue = 0; Field field = null; Method method = null; if (this.size() == 0) { return false; } Class dataClass = get(0).getClass(); String methodName = null; try { field = dataClass.getDeclaredField(fieldName); if (!field.isAccessible()) { throw new NoSuchFieldException(); } } catch (NoSuchFieldException noSuchFieldException) { //field not available. Use method invokation. try { methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1); method = dataClass.getMethod(methodName, null); } catch (NoSuchMethodException noSuchMethodException) { noSuchMethodException.printStackTrace(); return false; } } for (int index = 0; index < size() - 1; index++) { for (int nextIndex = index + 1; nextIndex < size(); nextIndex++) { current = get(index); next = get(nextIndex); //Check if current and next implements Comparable else can't compare. //so return without comparing.May be we can have an exception for this purpose. try { if (field != null && field.isAccessible()) { Comparable thisObj = (Comparable) field.get(current); Comparable otherObj = (Comparable) field.get(next); if (thisObj == null) { compareValue = -1; } else if (otherObj == null) { compareValue = 1; } else { if (thisObj instanceof String && ignoreCase) { compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj); } else { compareValue = thisObj.compareTo(otherObj); } } } else { Comparable thisObj = null; Comparable otherObj = null; if (methodName != null) { Method thisObjMethod = current.getClass().getMethod(methodName, null); Method otherObjMethod = next.getClass().getMethod(methodName, null); thisObj = (Comparable) thisObjMethod.invoke(current, null); otherObj = (Comparable) otherObjMethod.invoke(next, null); } else { thisObj = (Comparable) method.invoke(current, null); otherObj = (Comparable) method.invoke(next, null); } if (thisObj == null) { compareValue = -1; } else if (otherObj == null) { compareValue = 1; } else { if (thisObj instanceof String && ignoreCase) { compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj); } else { compareValue = thisObj.compareTo(otherObj); } } } } catch (IllegalAccessException illegalAccessException) { LOG.warn(illegalAccessException.getMessage()); return false; } catch (InvocationTargetException invocationTargetException) { LOG.warn(invocationTargetException.getMessage(), invocationTargetException); return false; } catch (SecurityException e) { LOG.warn(e.getMessage(), e); return false; } catch (NoSuchMethodException e) { LOG.warn(e.getMessage(), e); return false; } if (ascending && compareValue > 0) { E temp = get(index); set(index, get(nextIndex)); set(nextIndex, temp); } else if (!ascending && compareValue < 0) { E temp = get(index); set(index, get(nextIndex)); set(nextIndex, temp); } } } return true; }
From source file:org.apache.jcs.utils.struct.SortedPreferentialArray.java
/** * This method determines the position where an insert should take place for a given object. * With some additional checking, this can also be used to find an object matching or greater * than the argument./* w ww . java 2 s . c o m*/ * <p> * If the array is not full and the current object is larger than all the rest the first open * slot at the end will be returned. * <p> * NOTE: If the object is larger than the largest and it is full, it will return the last position. * <p> * If the array is empty, the first spot is returned. * <p> * If the object is smaller than all the rests, the first position is returned. The caller must * decide what to do given the preference. * <p> * Returns the position of the object nearest to or equal to the larger object. * <p> * If you want to find the takePosition, you have to calculate it. * findNearestOccupiedLargerOrEqualPosition will calculate this for you. * <p> * @param obj Comparable * @return int */ private int findNearestLargerEqualOrLastPosition(Comparable obj) { // do nothing if a null was passed in if (obj == null) { return -1; } // return the first spot if the array is empty if (curSize <= 0) { return 0; } // mark the numer to be returned, the greaterPos as unset int greaterPos = -1; // prepare for a binary search int curPos = (curSize - 1) / 2; int prevPos = -1; try { // set the loop exit flag to false boolean done = false; // check the ends // return insert position 0 if obj is smaller // than the smallest. the caller can determine what to // do with this, depending on the preference setting if (obj.compareTo(getSmallest()) <= 0) { // LESS THAN OR EQUAL TO SMALLEST if (log.isDebugEnabled()) { log.debug(obj + " is smaller than or equal to " + getSmallest()); } greaterPos = 0; done = true; // return greaterPos; } else { // GREATER THAN SMALLEST if (log.isDebugEnabled()) { log.debug(obj + " is bigger than " + getSmallest()); } // return the largest position if obj is larger // than the largest. the caller can determine what to // do with this, depending on the preference setting if (obj.compareTo(getLargest()) >= 0) { if (curSize == maxSize) { // there is no room left in the array, return the last // spot greaterPos = curSize - 1; done = true; } else { // there is room left in the array greaterPos = curSize; done = true; } } else { // the obj is less than or equal to the largest, so we know that the // last item is larger or equal greaterPos = curSize - 1; } } // ///////////////////////////////////////////////////////////////////// // begin binary search for insertion spot while (!done) { if (log.isDebugEnabled()) { log.debug("\n curPos = " + curPos + "; greaterPos = " + greaterPos + "; prevpos = " + prevPos); } // get out of loop if we have come to the end or passed it if (curPos == prevPos || curPos >= curSize) { done = true; break; } else // EQUAL TO // object at current position is equal to the obj, use this, // TODO could avoid some shuffling if I found a lower pos. if (array[curPos].compareTo(obj) == 0) { if (log.isDebugEnabled()) { log.debug(array[curPos] + " is equal to " + obj); } greaterPos = curPos; done = true; break; } else // GREATER THAN // array object at current position is greater than the obj, go // left if (array[curPos].compareTo(obj) > 0) { if (log.isDebugEnabled()) { log.debug(array[curPos] + " is greater than " + obj); } // set the smallest greater equal to the current position greaterPos = curPos; // set the current position to // set the previous position to the current position // We could have an integer overflow, but this array could // never get that large. int newPos = Math.min(curPos, (curPos + prevPos) / 2); prevPos = curPos; curPos = newPos; } else // LESS THAN // the object at the current position is smaller, go right if (array[curPos].compareTo(obj) < 0) { if (log.isDebugEnabled()) { log.debug(array[curPos] + " is less than " + obj); } if ((greaterPos != -1) && greaterPos - curPos < 0) { done = true; break; // return greaterPos; } else { int newPos = 0; if (prevPos > curPos) { newPos = Math.min((curPos + prevPos) / 2, curSize); } else if (prevPos == -1) { newPos = Math.min((curSize + curPos) / 2, curSize); } prevPos = curPos; curPos = newPos; } } } // end while // ///////////////////////////////////////////////////////////////////// if (log.isDebugEnabled()) { log.debug("Greater Position is [" + greaterPos + "]" + " array[greaterPos] [" + array[greaterPos] + "]"); } } catch (Exception e) { log.error("\n curPos = " + curPos + "; greaterPos = " + greaterPos + "; prevpos = " + prevPos + " " + this.dumpArray(), e); } return greaterPos; }
From source file:edu.umd.cfar.lamp.viper.util.Range.java
/** * Gets the range shared by this and the specified * range./*from w ww . j a v a 2 s.c om*/ * @param list the list to intersect with * @return the shared range */ public Range intersect(IntervalIndexList list) { // Note that each span in a range must // have a gap before it. this means it is // ease enough to just follow the heuristic: // get span to add, advance to latest pointer, // get span to add. Range newRange = new Range(); if (this.isEmpty() || list.isEmpty()) { return newRange; } SortedMap A = this.spans; Comparable aNextStart = (Comparable) A.firstKey(); Comparable aNextEnd = (Comparable) A.get(aNextStart); Iterator B = list.iterator(); if (!B.hasNext()) { return newRange; } Interval b = (Interval) B.next(); if (b.isEmpty()) { throw new AssertionError(); } Comparable bNextStart = b.getStart(); Comparable bNextEnd = b.getEnd(); while (aNextStart != null && bNextStart != null) { double diffStartStart = aNextStart.compareTo(bNextStart); double diffEndEnd = aNextEnd.compareTo(bNextEnd); if (diffStartStart == 0) { // both start at the same time if (diffEndEnd == 0) { newRange.add(aNextStart, aNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } else if (diffEndEnd < 0) { // a stops before b newRange.add(aNextStart, aNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); } else { // b stops before a newRange.add(bNextStart, bNextEnd); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } } else if (diffStartStart < 0) { // a starts before b double diffEndStart = aNextEnd.compareTo(bNextStart); if (diffEndStart <= 0) { // skip ahead, since there is no // chance of overlap here aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); } else if (diffEndEnd == 0) { newRange.add(bNextStart, bNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } else if (diffEndEnd < 0) { // a ends before b does, but after b starts newRange.add(bNextStart, aNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); } else { // a ends after b does newRange.add(bNextStart, bNextEnd); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } } else { // a starts after b does double diffStartEnd = aNextStart.compareTo(bNextEnd); if (diffStartEnd >= 0) { // skip ahead, since there is no // chance of overlap here bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } else if (diffEndEnd == 0) { // both end at the same moment newRange.add(aNextStart, aNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } else if (diffEndEnd < 0) { // a is a subset of b newRange.add(aNextStart, aNextEnd); aNextStart = this.firstAfterOrAt(aNextEnd); aNextEnd = this.endOf(aNextStart); } else { // a ends after b does newRange.add(aNextStart, bNextEnd); bNextStart = list.firstAfterOrAt(bNextEnd); bNextEnd = list.endOf(bNextStart); } } if ((aNextStart != null && bNextStart != null) && (aNextEnd == null || bNextEnd == null)) { throw new AssertionError(); } } return newRange; }
From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java
private void minRestriction(Comparable update, Comparable old, String propertyId) { // When minValue is restricted, throw an error boolean flag = false; String msg = propertyId + ":"; if (old == null) { if (update != null) { flag = true;//from w w w . j av a2 s . c o m } } else { if (update != null) { if (old.compareTo(update) < 0) { flag = true; } } } if (flag) { msg += "'minValue' cannot be further restricted"; constraint(msg); } }
From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java
private void maxRestriction(Comparable update, Comparable old, String propertyId, PropertyType propertyType) { // When minValue is restricted, throw an error boolean flag = false; String msg = propertyId + ":"; if (old == null) { if (update != null) { flag = true;// w w w . j av a 2 s .c o m } } else { if (update != null) { if (old.compareTo(update) > 0) { flag = true; } } } if (flag) { if (propertyType.equals(PropertyType.STRING)) { msg += "'maxLength' cannot be further restricted"; } else { msg += "'maxValue' cannot be further restricted"; } constraint(msg); } }
From source file:org.codhaus.groovy.grails.validation.ext.ConstrainedPropertyGunn.java
/** * @return Returns the max./* w ww. j a v a 2 s. c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Comparable getMax() { Comparable maxValue = null; MaxConstraint maxConstraint = (MaxConstraint) appliedConstraints.get(MAX_CONSTRAINT); RangeConstraint rangeConstraint = (RangeConstraint) appliedConstraints.get(RANGE_CONSTRAINT); if (maxConstraint != null || rangeConstraint != null) { Comparable maxConstraintValue = maxConstraint == null ? null : maxConstraint.getMaxValue(); Comparable rangeConstraintHighValue = rangeConstraint == null ? null : rangeConstraint.getRange().getTo(); if (maxConstraintValue != null && rangeConstraintHighValue != null) { maxValue = (maxConstraintValue.compareTo(rangeConstraintHighValue) < 0) ? maxConstraintValue : rangeConstraintHighValue; } else if (maxConstraintValue == null && rangeConstraintHighValue != null) { maxValue = rangeConstraintHighValue; } else if (maxConstraintValue != null && rangeConstraintHighValue == null) { maxValue = maxConstraintValue; } } return maxValue; }
From source file:org.codhaus.groovy.grails.validation.ext.ConstrainedPropertyGunn.java
/** * @return Returns the min./*from w w w.j a v a 2 s.c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Comparable getMin() { Comparable minValue = null; MinConstraint minConstraint = (MinConstraint) appliedConstraints.get(MIN_CONSTRAINT); RangeConstraint rangeConstraint = (RangeConstraint) appliedConstraints.get(RANGE_CONSTRAINT); if (minConstraint != null || rangeConstraint != null) { Comparable minConstraintValue = minConstraint != null ? minConstraint.getMinValue() : null; Comparable rangeConstraintLowValue = rangeConstraint != null ? rangeConstraint.getRange().getFrom() : null; if (minConstraintValue != null && rangeConstraintLowValue != null) { minValue = (minConstraintValue.compareTo(rangeConstraintLowValue) > 0) ? minConstraintValue : rangeConstraintLowValue; } else if (minConstraintValue == null && rangeConstraintLowValue != null) { minValue = rangeConstraintLowValue; } else if (minConstraintValue != null && rangeConstraintLowValue == null) { minValue = minConstraintValue; } } return minValue; }
From source file:grails.validation.ConstrainedProperty.java
/** * @return Returns the max./*from ww w. j ava 2s . c om*/ */ @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Comparable getMax() { Comparable maxValue = null; MaxConstraint maxConstraint = (MaxConstraint) appliedConstraints.get(MAX_CONSTRAINT); RangeConstraint rangeConstraint = (RangeConstraint) appliedConstraints.get(RANGE_CONSTRAINT); if (maxConstraint != null || rangeConstraint != null) { Comparable maxConstraintValue = maxConstraint == null ? null : maxConstraint.getMaxValue(); Comparable rangeConstraintHighValue = rangeConstraint == null ? null : rangeConstraint.getRange().getTo(); if (maxConstraintValue != null && rangeConstraintHighValue != null) { maxValue = (maxConstraintValue.compareTo(rangeConstraintHighValue) < 0) ? maxConstraintValue : rangeConstraintHighValue; } else if (maxConstraintValue == null && rangeConstraintHighValue != null) { maxValue = rangeConstraintHighValue; } else if (maxConstraintValue != null && rangeConstraintHighValue == null) { maxValue = maxConstraintValue; } } return maxValue; }
From source file:grails.validation.ConstrainedProperty.java
/** * @return Returns the min./* ww w . j ava 2 s . c o m*/ */ @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Comparable getMin() { Comparable minValue = null; MinConstraint minConstraint = (MinConstraint) appliedConstraints.get(MIN_CONSTRAINT); RangeConstraint rangeConstraint = (RangeConstraint) appliedConstraints.get(RANGE_CONSTRAINT); if (minConstraint != null || rangeConstraint != null) { Comparable minConstraintValue = minConstraint != null ? minConstraint.getMinValue() : null; Comparable rangeConstraintLowValue = rangeConstraint != null ? rangeConstraint.getRange().getFrom() : null; if (minConstraintValue != null && rangeConstraintLowValue != null) { minValue = (minConstraintValue.compareTo(rangeConstraintLowValue) > 0) ? minConstraintValue : rangeConstraintLowValue; } else if (minConstraintValue == null && rangeConstraintLowValue != null) { minValue = rangeConstraintLowValue; } else if (minConstraintValue != null && rangeConstraintLowValue == null) { minValue = minConstraintValue; } } return minValue; }
From source file:org.ofbiz.core.entity.GenericEntity.java
/** * Compares this GenericEntity to the passed object * * @param obj Object to compare this to/*from w w w .j a v a 2 s.c om*/ * @return int representing the result of the comparison (-1,0, or 1) */ public int compareTo(GenericEntity obj) { // if null, it will push to the beginning if (obj == null) return -1; // rather than doing an if instanceof, just cast it and let it throw an exception if // it fails, this will be faster for the expected case (that it IS a GenericEntity) // if not a GenericEntity throw ClassCastException, as the spec says int tempResult = this.entityName.compareTo(obj.entityName); // if they did not match, we know the order, otherwise compare the primary keys if (tempResult != 0) return tempResult; // both have same entityName, should be the same so let's compare PKs int pksSize = modelEntity.getPksSize(); for (int i = 0; i < pksSize; i++) { ModelField curField = modelEntity.getPk(i); Comparable thisVal = (Comparable<?>) this.fields.get(curField.getName()); Comparable thatVal = (Comparable<?>) obj.fields.get(curField.getName()); if (thisVal == null) { if (thatVal == null) tempResult = 0; // if thisVal is null, but thatVal is not, return 1 to put this earlier in the list else tempResult = 1; } else { // if thatVal is null, put the other earlier in the list if (thatVal == null) tempResult = -1; else tempResult = thisVal.compareTo(thatVal); } if (tempResult != 0) return tempResult; } // okay, if we got here it means the primaryKeys are exactly the SAME, so compare the rest of the fields int nopksSize = modelEntity.getNopksSize(); for (int i = 0; i < nopksSize; i++) { ModelField curField = modelEntity.getNopk(i); Comparable thisVal = (Comparable<?>) this.fields.get(curField.getName()); Comparable thatVal = (Comparable<?>) obj.fields.get(curField.getName()); if (thisVal == null) { if (thatVal == null) tempResult = 0; // if thisVal is null, but thatVal is not, return 1 to put this earlier in the list else tempResult = 1; } else { // if thatVal is null, put the other earlier in the list if (thatVal == null) tempResult = -1; else tempResult = thisVal.compareTo(thatVal); } if (tempResult != 0) return tempResult; } // if we got here it means the two are exactly the same, so return tempResult, which should be 0 return tempResult; }