下面列出了java.util.ListIterator#previous ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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();
}
};
}
/**
* 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);
}
}
}
@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);
}
}
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;
}
/**
* 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;
}
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;
}
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;
}
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));
}
/**
* 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);
}
}
}
}
/**
* 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;
}
@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(); }
};
}
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());
}
}
/**
* 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;
}
}
}
}
/**
* 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;
}
}
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;
}
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();
}
/**
* 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;
}
}