java.util.ListIterator#previous ( )源码实例Demo

下面列出了java.util.ListIterator#previous ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: qpid-broker-j   文件: RangeSetImpl.java
@Override
public void add(Range range)
{
    ListIterator<Range> it = ranges.listIterator();

    while (it.hasNext())
    {
        Range next = it.next();
        if (range.touches(next))
        {
            it.remove();
            range = range.span(next);
        }
        else if (lt(range.getUpper(), next.getLower()))
        {
            it.previous();
            it.add(range);
            return;
        }
    }

    it.add(range);
}
 
源代码2 项目: openjdk-8-source   文件: ListAdapter.java
@Override
public final Iterator<Object> descendingIterator() {
    final ListIterator<Object> it = listIterator(size());
    return new Iterator<Object>() {
        @Override
        public boolean hasNext() {
            return it.hasPrevious();
        }

        @Override
        public Object next() {
            return it.previous();
        }

        @Override
        public void remove() {
            it.remove();
        }
    };
}
 
源代码3 项目: scipio-erp   文件: ContactMechPurposeInfo.java
/**
 * Gets the values that have occurrences closest to given target count.
 * Above the count is always preferred to below the count, but exact is preferred to above.
 * TODO: VERIFY this works.
 */
static Set<String> getClosestValuesByCount(Map<String, Integer> counts, int targetCount) {
    Map<Integer, Set<String>> countMechs = makeCountValueMap(counts);
    if (countMechs.isEmpty()) {
        return Collections.emptySet();
    }
    List<Integer> highToLowCounts = new ArrayList<>(countMechs.keySet());
    Collections.sort(highToLowCounts, Collections.reverseOrder());

    ListIterator<Integer> it = highToLowCounts.listIterator();
    int count = it.next();
    while(it.hasNext() && (count = it.next()) >= targetCount) {
        ;
    }
    if (count >= targetCount) {
        return countMechs.get(count);
    } else {
        it.previous(); // discard to go back one
        if (it.hasPrevious()) {
            return countMechs.get(it.previous());
        } else {
            return countMechs.get(count);
        }
    }
}
 
源代码4 项目: sailfish-core   文件: FileMessageLoader.java
@Override
protected void retrieveMessages(Queue<FileMessage> forMessages, int count, long lastID) {
    if(lastID == -1 || lastID == source.size()) {
        return;
    }

    try {
        ListIterator<FileMessage> it = source.listIterator((int)lastID);

        while(count > 0 && (ascending ? it.hasNext() : it.hasPrevious())) {
            FileMessage message = ascending ? it.next() : it.previous();

            if(!checkMessage(message, filter)) {
                continue;
            }

            forMessages.add(message);
            count--;
        }

        nextIndex = ascending ? it.nextIndex() : it.previousIndex();
    } catch(IndexOutOfBoundsException | NoSuchElementException e) {
        throw new StorageException("Message list probably have been cleared", e);
    }
}
 
源代码5 项目: Mupdf   文件: DocPageView.java
public NoteAnnotation getSelectedNoteAnnotation()
{
	if (mAnnotations != null)
	{
		//  iterate in reverse order
		ListIterator<PageAnnotation> li = mAnnotations.listIterator(mAnnotations.size());
		while (li.hasPrevious())
		{
			PageAnnotation annot = li.previous();
			if ((annot instanceof NoteAnnotation) && annot.isSelected())
			{
				return (NoteAnnotation)annot;
			}
		}
	}

	return null;
}
 
源代码6 项目: j2objc   文件: ICUService.java
/**
 * Return a map from visible ids to factories.
 */
private Map<String, Factory> getVisibleIDMap() {
    synchronized (this) { // or idcache-only lock?
        if (idcache == null) {
            try {
                factoryLock.acquireRead();
                Map<String, Factory> mutableMap = new HashMap<String, Factory>();
                ListIterator<Factory> lIter = factories.listIterator(factories.size());
                while (lIter.hasPrevious()) {
                    Factory f = lIter.previous();
                    f.updateVisibleIDs(mutableMap);
                }
                this.idcache = Collections.unmodifiableMap(mutableMap);
            } finally {
                factoryLock.releaseRead();
            }
        }
    }
    return idcache;
}
 
源代码7 项目: es6draft   文件: ExpressionGenerator.java
private int arrayLiteral(ListIterator<Expression> iterator, CodeVisitor mv) {
    int nextIndex = 0;
    while (iterator.hasNext()) {
        Expression element = iterator.next();
        if (element instanceof Elision) {
            // Elision
        } else if (element instanceof SpreadElement) {
            iterator.previous(); // step back
            break;
        } else {
            mv.dup();
            mv.iconst(nextIndex);
            ArrayAccumulationElement(element, mv);
        }
        nextIndex += 1;
    }
    return nextIndex;
}
 
源代码8 项目: immutables   文件: Code.java
static List<Term> replaceReturn(List<Term> code, String replacement) {
  ArrayList<Term> result = new ArrayList<>(code);
  ListIterator<Term> it = result.listIterator();
  boolean wasReturn = false;
  while (it.hasNext()) {
    Term t = it.next();
    if (t.isWordOrNumber() && t.is("return")) {
      it.set(new Other(replacement));
      wasReturn = true;
    }
  }
  if (!wasReturn) {
    ListIterator<Term> revIt = Lists.reverse(result).listIterator();
    if (nextNonBlankIs(revIt, "}")) {
      nextNonBlankIs(revIt, ";");
      revIt.previous();
      revIt.add(new Delimiter(";"));
      revIt.add(new Other(replacement));
      revIt.add(new Whitespace("\n"));
    }
  }
  return result;
}
 
源代码9 项目: Markwon   文件: StaggeredDelimiterProcessor.java
void add(DelimiterProcessor dp) {
    final int len = dp.getMinLength();
    ListIterator<DelimiterProcessor> it = processors.listIterator();
    boolean added = false;
    while (it.hasNext()) {
        DelimiterProcessor p = it.next();
        int pLen = p.getMinLength();
        if (len > pLen) {
            it.previous();
            it.add(dp);
            added = true;
            break;
        } else if (len == pLen) {
            throw new IllegalArgumentException("Cannot add two delimiter processors for char '" + delim + "' and minimum length " + len);
        }
    }
    if (!added) {
        processors.add(dp);
        this.minLength = len;
    }
}
 
@Test
public void indexedListIteratorInMiddleHasNextAndHasPreviousOnThreeElementsList_shouldReturnTrueForEachElement() {
    final ObservableArrayList<String> list = new ObservableArrayList<>("1", "2", "3");
    final ListIterator<String> iterator = list.listIterator(1);

    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.next();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.next();
    assertThat(iterator.hasNext(), is(false));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(false));
}
 
源代码11 项目: scipio-erp   文件: FormRenderer.java
/**
 * SCIPIO: Renders the given modelFormField (within the open cell) if it passes shouldUse condition;
 * in addition, if the following fields have the same name, they are also rendered and
 * consumed from the formFieldsIt list iterator.
 * <p>
 * This is needed because we could have several fields of same name
 * in a row with different use-when expressions. In such case, we must render
 * exactly one cell for all of them (at most one, but one is always required also).
 * We must process the fields having same name as a "batch" here.
 * <p>
 * Added 2018-03-02.
 */
private void renderItemRowCellFields(Appendable writer, Map<String, Object> localContext, FormStringRenderer formStringRenderer,
        ModelFormField modelFormField, ListIterator<ModelFormField> formFieldsIt, boolean forceUse) throws IOException {
    List<ModelFormField> sameNameFields = null;
    String modelFormFieldName = modelFormField.getName();
    while(formFieldsIt.hasNext()) {
        ModelFormField nextField = formFieldsIt.next();
        if (modelFormFieldName.equals(nextField.getName())) {
            if (sameNameFields == null) sameNameFields = new ArrayList<>();
            sameNameFields.add(nextField);
        } else {
            formFieldsIt.previous();
            break;
        }
    }

    if (forceUse || modelFormField.shouldUse(localContext)) {
        modelFormField.renderFieldString(writer, localContext, formStringRenderer);
    }
    if (sameNameFields != null) {
        for(ModelFormField sameNameField : sameNameFields) {
            if (forceUse || sameNameField.shouldUse(localContext)) {
                sameNameField.renderFieldString(writer, localContext, formStringRenderer);
            }
        }
    }
}
 
源代码12 项目: flink   文件: CompletedCheckpointStore.java
/**
 * Returns the latest {@link CompletedCheckpoint} instance or <code>null</code> if none was
 * added.
 */
default CompletedCheckpoint getLatestCheckpoint(boolean isPreferCheckpointForRecovery) throws Exception {
	if (getAllCheckpoints().isEmpty()) {
		return null;
	}

	CompletedCheckpoint candidate = getAllCheckpoints().get(getAllCheckpoints().size() - 1);
	if (isPreferCheckpointForRecovery && getAllCheckpoints().size() > 1) {
		List<CompletedCheckpoint> allCheckpoints;
		try {
			allCheckpoints = getAllCheckpoints();
			ListIterator<CompletedCheckpoint> listIterator = allCheckpoints.listIterator(allCheckpoints.size() - 1);
			while (listIterator.hasPrevious()) {
				CompletedCheckpoint prev = listIterator.previous();
				if (!prev.getProperties().isSavepoint()) {
					candidate = prev;
					LOG.info("Found a completed checkpoint before the latest savepoint, will use it to recover!");
					break;
				}
			}
		} catch (Exception e) {
			LOG.error("Method getAllCheckpoints caused exception : ", e);
			throw new FlinkRuntimeException(e);
		}
	}

	return candidate;
}
 
源代码13 项目: gravitee-gateway   文件: ResponsePolicyChain.java
@Override
public Iterator<Policy> iterator() {
    final ListIterator<Policy> listIterator = policies.listIterator(policies.size());
    return new Iterator<Policy>() {
        @Override
        public boolean hasNext() { return listIterator.hasPrevious(); }

        @Override
        public Policy next() { return listIterator.previous(); }

        @Override
        public void remove() { listIterator.remove(); }
    };
}
 
源代码14 项目: servicecomb-pack   文件: TxEntities.java
public void forEachReverse(BiConsumer<String, TxEntity> action) {
  ListIterator<Map.Entry<String, TxEntity>> iterator = new ArrayList<>(entities.entrySet()).listIterator(entities.size());
  while (iterator.hasPrevious()) {
    Map.Entry<String, TxEntity> entry = iterator.previous();
    action.accept(entry.getKey(),entry.getValue());
  }
}
 
源代码15 项目: sakai   文件: Revision.java
/**
 * Applies the series of deltas in this revision as patches to
 * the given text.
 * @param target the text to patch.
 * @throws PatchFailedException if any of the patches cannot be applied.
 */
public synchronized void applyTo(List target) throws PatchFailedException
{
    ListIterator i = deltas_.listIterator(deltas_.size());
    while (i.hasPrevious())
    {
        Delta delta = (Delta) i.previous();
        delta.patch(target);
    }
}
 
/**
 * Releases for normal dispatching to the current focus owner all
 * KeyEvents which were enqueued because of a call to
 * <code>enqueueKeyEvents</code> with the same timestamp and Component.
 * If the given timestamp is less than zero, the outstanding enqueue
 * request for the given Component with the <b>oldest</b> timestamp (if
 * any) should be cancelled.
 *
 * @param after the timestamp specified in the call to
 *        <code>enqueueKeyEvents</code>, or any value < 0
 * @param untilFocused the Component specified in the call to
 *        <code>enqueueKeyEvents</code>
 * @see #enqueueKeyEvents
 * @see #discardKeyEvents
 */
protected synchronized void dequeueKeyEvents(long after,
                                             Component untilFocused) {
    if (untilFocused == null) {
        return;
    }

    focusLog.finer("Dequeue at {0} for {1}",
                   after, untilFocused);

    TypeAheadMarker marker;
    ListIterator iter = typeAheadMarkers.listIterator
        ((after >= 0) ? typeAheadMarkers.size() : 0);

    if (after < 0) {
        while (iter.hasNext()) {
            marker = (TypeAheadMarker)iter.next();
            if (marker.untilFocused == untilFocused)
            {
                iter.remove();
                return;
            }
        }
    } else {
        while (iter.hasPrevious()) {
            marker = (TypeAheadMarker)iter.previous();
            if (marker.untilFocused == untilFocused &&
                marker.after == after)
            {
                iter.remove();
                return;
            }
        }
    }
}
 
源代码17 项目: dsl-compiler-client   文件: diff_match_patch.java
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c&lt;ins&gt;at c&lt;/ins&gt;ame. -&gt; The &lt;ins&gt;cat &lt;/ins&gt;came.
 * @param diffs LinkedList of Diff objects.
 */
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
    String equality1, edit, equality2;
    String commonString;
    int commonOffset;
    int score, bestScore;
    String bestEquality1, bestEdit, bestEquality2;
    // Create a new iterator at the start.
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
    Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
    Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
    // Intentionally ignore the first and last element (don't need checking).
    while (nextDiff != null) {
        if (prevDiff.operation == Operation.EQUAL &&
                nextDiff.operation == Operation.EQUAL) {
            // This is a single edit surrounded by equalities.
            equality1 = prevDiff.text;
            edit = thisDiff.text;
            equality2 = nextDiff.text;

            // First, shift the edit as far left as possible.
            commonOffset = diff_commonSuffix(equality1, edit);
            if (commonOffset != 0) {
                commonString = edit.substring(edit.length() - commonOffset);
                equality1 = equality1.substring(0, equality1.length() - commonOffset);
                edit = commonString + edit.substring(0, edit.length() - commonOffset);
                equality2 = commonString + equality2;
            }

            // Second, step character by character right, looking for the best fit.
            bestEquality1 = equality1;
            bestEdit = edit;
            bestEquality2 = equality2;
            bestScore = diff_cleanupSemanticScore(equality1, edit)
                    + diff_cleanupSemanticScore(edit, equality2);
            while (edit.length() != 0 && equality2.length() != 0
                    && edit.charAt(0) == equality2.charAt(0)) {
                equality1 += edit.charAt(0);
                edit = edit.substring(1) + equality2.charAt(0);
                equality2 = equality2.substring(1);
                score = diff_cleanupSemanticScore(equality1, edit)
                        + diff_cleanupSemanticScore(edit, equality2);
                // The >= encourages trailing rather than leading whitespace on edits.
                if (score >= bestScore) {
                    bestScore = score;
                    bestEquality1 = equality1;
                    bestEdit = edit;
                    bestEquality2 = equality2;
                }
            }

            if (!prevDiff.text.equals(bestEquality1)) {
                // We have an improvement, save it back to the diff.
                if (bestEquality1.length() != 0) {
                    prevDiff.text = bestEquality1;
                } else {
                    pointer.previous(); // Walk past nextDiff.
                    pointer.previous(); // Walk past thisDiff.
                    pointer.previous(); // Walk past prevDiff.
                    pointer.remove(); // Delete prevDiff.
                    pointer.next(); // Walk past thisDiff.
                    pointer.next(); // Walk past nextDiff.
                }
                thisDiff.text = bestEdit;
                if (bestEquality2.length() != 0) {
                    nextDiff.text = bestEquality2;
                } else {
                    pointer.remove(); // Delete nextDiff.
                    nextDiff = thisDiff;
                    thisDiff = prevDiff;
                }
            }
        }
        prevDiff = thisDiff;
        thisDiff = nextDiff;
        nextDiff = pointer.hasNext() ? pointer.next() : null;
    }
}
 
private byte[] readClusters(List<Long> clusters)
{
    int maxLength = 16384; // Linux/libusb internally can only handle a buffer of 16834 for bulk transfers
    int maxClusters = (int) (maxLength / (reservedRegion.getBytesPerSector() * reservedRegion.getSectorsPerCluster()));
    long firstClusterLba = partition.getLbaStart() + reservedRegion.getNumberReservedSectors()
            + (reservedRegion.getFatCopies() * reservedRegion.getNumberSectorsPerFat());

    int lengthData = clusters.size() * ((int) (reservedRegion.getSectorsPerCluster() * reservedRegion.getBytesPerSector()));
    byte[] data = new byte[lengthData];

    ListIterator<Long> e = clusters.listIterator();
    int pointer = 0;

    while(e.hasNext())
    {
        long cluster = e.next();
        int i = 1;
        boolean keep = true;
        while(i < maxClusters && keep)
        {
            if(e.hasNext())
            {
                if(cluster == e.next() - i)
                    i++;
                else
                {
                    if(e.hasPrevious())
                        e.previous();
                    keep = false;
                }
            }else
            {
                keep = false;
            }
        }

        long lbaCluster = firstClusterLba + (cluster - 2) * reservedRegion.getSectorsPerCluster();
        int clustersLength = i *  (int) (reservedRegion.getSectorsPerCluster());
        int bufferLength = clustersLength * ((int) reservedRegion.getBytesPerSector());

        byte[] rawClusters = readBytes(lbaCluster, clustersLength);
        if(rawClusters == null)
            return null;

        System.arraycopy(rawClusters, 0, data, pointer, bufferLength);

        pointer += bufferLength;
    }
    return data;
}
 
源代码19 项目: MHAP   文件: RandomSequenceGenerator.java
public String addError(String str, double insertionRate, double deletionRate, double substitutionRate)
{
	if (insertionRate < 0.0 || deletionRate < 0.0 || substitutionRate < 0.0)
		throw new MhapRuntimeException("Error rate cannot be negative.");
	
	if (insertionRate+deletionRate+substitutionRate>1.00001)
		throw new MhapRuntimeException("Error rate must be less than or equal to 1.0.");

	double errorRate = insertionRate + deletionRate + substitutionRate;

	// use a linked list for insertions
	LinkedList<Character> modifiedSequence = new LinkedList<>();
	for (char a : str.toCharArray())
		modifiedSequence.add(a);

	// now mutate
	ListIterator<Character> iter = modifiedSequence.listIterator();
	while (iter.hasNext())
	{
		char i = iter.next();

		if (randGenerator.nextDouble() < errorRate)
		{
			double errorType = randGenerator.nextDouble();
			if (errorType < substitutionRate)
			{ // mismatch
				// switch base

				iter.set(getRandomBase(i));

				i++;
			}
			else if (errorType < insertionRate + substitutionRate)
			{ // insert

				iter.previous();
				iter.add(getRandomBase(null));
			}
			else
			{ // delete

				iter.remove();
			}
		}
		else
		{
			// i++;
		}
	}

	StringBuilder returnedString = new StringBuilder(modifiedSequence.size());
	for (char c : modifiedSequence)
		returnedString.append(c);

	return returnedString.toString();
}
 
源代码20 项目: PowerFileExplorer   文件: DiffMatchPatch.java
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 * @param diffs LinkedList of Diff objects.
 */
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
	String equality1, edit, equality2;
	String commonString;
	int commonOffset;
	int score, bestScore;
	String bestEquality1, bestEdit, bestEquality2;
	// Create a new iterator at the start.
	ListIterator<Diff> pointer = diffs.listIterator();
	Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
	Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
	Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
	// Intentionally ignore the first and last element (don't need checking).
	while (nextDiff != null) {
		if (prevDiff.operation == Operation.EQUAL &&
			nextDiff.operation == Operation.EQUAL) {
			// This is a single edit surrounded by equalities.
			equality1 = prevDiff.text;
			edit = thisDiff.text;
			equality2 = nextDiff.text;

			// First, shift the edit as far left as possible.
			commonOffset = diff_commonSuffix(equality1, edit);
			if (commonOffset != 0) {
				commonString = edit.substring(edit.length() - commonOffset);
				equality1 = equality1.substring(0, equality1.length() - commonOffset);
				edit = commonString + edit.substring(0, edit.length() - commonOffset);
				equality2 = commonString + equality2;
			}

			// Second, step character by character right, looking for the best fit.
			bestEquality1 = equality1;
			bestEdit = edit;
			bestEquality2 = equality2;
			bestScore = diff_cleanupSemanticScore(equality1, edit)
				+ diff_cleanupSemanticScore(edit, equality2);
			while (edit.length() != 0 && equality2.length() != 0
				   && edit.charAt(0) == equality2.charAt(0)) {
				equality1 += edit.charAt(0);
				edit = edit.substring(1) + equality2.charAt(0);
				equality2 = equality2.substring(1);
				score = diff_cleanupSemanticScore(equality1, edit)
					+ diff_cleanupSemanticScore(edit, equality2);
				// The >= encourages trailing rather than leading whitespace on edits.
				if (score >= bestScore) {
					bestScore = score;
					bestEquality1 = equality1;
					bestEdit = edit;
					bestEquality2 = equality2;
				}
			}

			if (!prevDiff.text.equals(bestEquality1)) {
				// We have an improvement, save it back to the diff.
				if (bestEquality1.length() != 0) {
					prevDiff.text = bestEquality1;
				} else {
					pointer.previous(); // Walk past nextDiff.
					pointer.previous(); // Walk past thisDiff.
					pointer.previous(); // Walk past prevDiff.
					pointer.remove(); // Delete prevDiff.
					pointer.next(); // Walk past thisDiff.
					pointer.next(); // Walk past nextDiff.
				}
				thisDiff.text = bestEdit;
				if (bestEquality2.length() != 0) {
					nextDiff.text = bestEquality2;
				} else {
					pointer.remove(); // Delete nextDiff.
					nextDiff = thisDiff;
					thisDiff = prevDiff;
				}
			}
		}
		prevDiff = thisDiff;
		thisDiff = nextDiff;
		nextDiff = pointer.hasNext() ? pointer.next() : null;
	}
}