Java Code Examples for java.util.ListIterator#set()

The following examples show how to use java.util.ListIterator#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Record.java    From swim with Apache License 2.0 6 votes vote down vote up
public Value put(String key, Value newValue) {
  final ListIterator<Item> items = listIterator();
  while (items.hasNext()) {
    final Item item = items.next();
    if (item instanceof Field && item.keyEquals(key)) {
      final Field field = (Field) item;
      if (field.isMutable()) {
        return field.setValue(newValue);
      } else {
        final Value oldValue = field.toValue();
        items.set(field.updatedValue(newValue));
        return oldValue;
      }
    }
  }
  add(new Slot(Text.from(key), newValue));
  return Value.absent();
}
 
Example 2
Source File: Record.java    From swim with Apache License 2.0 6 votes vote down vote up
@Override
public Record updatedSlot(Value key, Value value) {
  final Record record = isMutable() ? this : branch();
  final ListIterator<Item> items = record.listIterator();
  while (items.hasNext()) {
    final Item item = items.next();
    if (item.keyEquals(key)) {
      if (item instanceof Slot && item.isMutable()) {
        ((Slot) item).setValue(value);
      } else {
        items.set(new Slot(key, value));
      }
      return record;
    }
  }
  record.add(new Slot(key, value));
  return record;
}
 
Example 3
Source File: Record.java    From swim with Apache License 2.0 6 votes vote down vote up
public Value putAttr(Text key, Value newValue) {
  final ListIterator<Item> items = listIterator();
  while (items.hasNext()) {
    final Item item = items.next();
    if (item instanceof Field && item.keyEquals(key)) {
      if (item instanceof Attr && item.isMutable()) {
        return ((Attr) item).setValue(newValue);
      } else {
        final Value oldValue = item.toValue();
        items.set(new Attr(key, newValue));
        return oldValue;
      }
    }
  }
  add(new Attr(key, newValue));
  return Value.absent();
}
 
Example 4
Source File: TestList.java    From jtransc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the {@link ListIterator#set(Object)} method of the list iterator.
 */
public void testListIteratorSet() {
    if (!isSetSupported())
        return;

    Object[] elements = getFullElements();

    resetFull();
    ListIterator iter1 = getList().listIterator();
    ListIterator iter2 = getConfirmedList().listIterator();
    for (int i = 0; i < elements.length; i++) {
        iter1.next();
        iter2.next();
        iter1.set(elements[i]);
        iter2.set(elements[i]);
        verify();
    }
}
 
Example 5
Source File: ConfigRepositoryImpl.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static List<PluginConfig> buildPluginConfigs(PluginConfig updatedConfig,
        String priorVersion, AgentConfig agentConfig) throws OptimisticLockException {
    List<PluginConfig> pluginConfigs =
            Lists.newArrayList(agentConfig.getPluginConfigList());
    ListIterator<PluginConfig> i = pluginConfigs.listIterator();
    boolean found = false;
    while (i.hasNext()) {
        PluginConfig pluginConfig = i.next();
        if (pluginConfig.getId().equals(updatedConfig.getId())) {
            String existingVersion = Versions.getVersion(pluginConfig);
            if (!priorVersion.equals(existingVersion)) {
                throw new OptimisticLockException();
            }
            i.set(buildPluginConfig(pluginConfig, updatedConfig.getPropertyList(), true));
            found = true;
            break;
        }
    }
    if (found) {
        return pluginConfigs;
    } else {
        throw new IllegalStateException("Plugin config not found: " + updatedConfig.getId());
    }
}
 
Example 6
Source File: ListShuffleBenchmark.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * A list shuffle using an iterator.
 *
 * @param rng Random number generator.
 * @param list List.
 */
@SuppressWarnings({"rawtypes", "unchecked"})
private static void shuffleIterator(UniformRandomProvider rng, List<?> list) {
    final Object[] array = list.toArray();

    // Shuffle array
    for (int i = array.length; i > 1; i--) {
        swap(array, i - 1, rng.nextInt(i));
    }

    // Copy back. Use raw types.
    final ListIterator it = list.listIterator();
    for (final Object value : array) {
        it.next();
        it.set(value);
    }
}
 
Example 7
Source File: RBCFactory.java    From org.alloytools.alloy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a boolean value with the same meaning as the given accumulator.
 *
 * @requires acc.components in (this.values + this.values.negation +
 *           BooleanConstant)
 * @return v: BooleanValue | [[v]] = [[acc]]
 * @ensures v in BooleanFormula - NotGate => this.values' = this.values + v,
 *          this.values' = this.values
 * @throws NullPointerException any of the arguments are null
 */
BooleanValue assemble(BooleanAccumulator acc) {
    final int asize = acc.size();
    final Operator.Nary op = acc.op;
    switch (asize) {
        case 0 :
            return op.identity();
        case 1 :
            return acc.iterator().next();
        case 2 :
            final Iterator<BooleanValue> inputs = acc.iterator();
            return assemble(op, inputs.next(), inputs.next());
        default :
            final List<BooleanValue> vals = new LinkedList<BooleanValue>();
            for (BooleanValue v : acc) {
                vals.add(v);
            }
            while (vals.size() > 1) {
                final ListIterator<BooleanValue> itr = vals.listIterator();
                for (int i = 0, max = vals.size() - 1; i < max; i += 2) {
                    final BooleanValue v0 = itr.next();
                    itr.remove();
                    final BooleanValue v1 = itr.next();
                    final BooleanValue v0opv1 = assemble(op, v0, v1);
                    if (v0opv1 == op.shortCircuit())
                        return op.shortCircuit();
                    else if (v0opv1 == op.identity())
                        itr.remove();
                    else
                        itr.set(v0opv1);
                }
            }
            return vals.get(0);
    }
}
 
Example 8
Source File: LinkedListMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>If any entries for the specified {@code key} already exist in the
 * multimap, their values are changed in-place without affecting the iteration
 * order.
 *
 * <p>The returned list is immutable and implements
 * {@link java.util.RandomAccess}.
 */

@CanIgnoreReturnValue
@Override
public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) {
  List<V> oldValues = getCopy(key);
  ListIterator<V> keyValues = new ValueForKeyIterator(key);
  Iterator<? extends V> newValues = values.iterator();

  // Replace existing values, if any.
  while (keyValues.hasNext() && newValues.hasNext()) {
    keyValues.next();
    keyValues.set(newValues.next());
  }

  // Remove remaining old values, if any.

  while (keyValues.hasNext()) {
    keyValues.next();
    keyValues.remove();
  }

  // Add remaining new values, if any.

  while (newValues.hasNext()) {
    keyValues.add(newValues.next());
  }
  return oldValues;
}
 
Example 9
Source File: SubList.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "modifiable",
      expectedExceptions = ConcurrentModificationException.class)
public void testModListIteratorSet(List<Integer> list, int from, int to) {
    List<Integer> subList = list.subList(from, to);
    ListIterator<Integer> it = subList.listIterator();
    it.next();
    list.add(42);
    it.set(42);
}
 
Example 10
Source File: SubList.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "unsettable",
      expectedExceptions = UnsupportedOperationException.class)
public void testUnmodListIteratorSetPrevious(List<Integer> list, int from, int to) {
    List<Integer> subList = list.subList(from, to);
    ListIterator<Integer> it = subList.listIterator(to - from);
    it.previous();
    it.set(42);
}
 
Example 11
Source File: ForwardState.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked") // Safe casts assuming clone() works correctly
public Object clone() {
    try {
        ForwardState clonedState = (ForwardState) super.clone();

        /* clone checkers, if cloneable */
        clonedState.forwardCheckers = (ArrayList<PKIXCertPathChecker>)
                                            forwardCheckers.clone();
        ListIterator<PKIXCertPathChecker> li =
                            clonedState.forwardCheckers.listIterator();
        while (li.hasNext()) {
            PKIXCertPathChecker checker = li.next();
            if (checker instanceof Cloneable) {
                li.set((PKIXCertPathChecker)checker.clone());
            }
        }

        /*
         * Shallow copy traversed names. There is no need to
         * deep copy contents, since the elements of the Set
         * are never modified by subsequent calls to updateState().
         */
        clonedState.subjectNamesTraversed
            = (HashSet<GeneralNameInterface>)subjectNamesTraversed.clone();
        return clonedState;
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e.toString(), e);
    }
}
 
Example 12
Source File: Scripting.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<ScriptEngineFactory> getEngineFactories() {
    List<ScriptEngineFactory> all = new ArrayList<>();
    all.addAll(super.getEngineFactories());
    all.addAll(extra);
    ListIterator<ScriptEngineFactory> it = all.listIterator();
    while (it.hasNext()) {
        ScriptEngineFactory f = it.next();
        if (f.getNames().contains("Graal.js") || isNashornFactory(f)) { // NOI18N
            it.set(new GraalJSWrapperFactory(f));
        }
    }
    return all;
}
 
Example 13
Source File: HtmlNode.java    From zongtui-webcrawler with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Only document can be select
 * See: https://github.com/code4craft/webmagic/issues/113
 *
 * @param elementIterator
 * @param element
 */
private Element checkElementAndConvert(ListIterator<Element> elementIterator) {
    Element element = elementIterator.next();
    if (!(element instanceof Document)) {
        Document root = new Document(element.ownerDocument().baseUri());
        Element clone = element.clone();
        root.appendChild(clone);
        elementIterator.set(root);
        return root;
    }
    return element;
}
 
Example 14
Source File: QueryCanonicalizer.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** 
 * Handle FALSE items in the immediate children of this
 * 
 * @return true if this composite was replaced by FALSE
 */
private static boolean collapseFalse(CompositeItem composite, ListIterator<Item> parentIterator) {
    if ( ! containsFalse(composite)) return false;

    if (composite instanceof AndItem) { // AND false is always false
        parentIterator.set(new FalseItem());
        return true;
    }
    else if (composite instanceof OrItem) { // OR false is unnecessary
        removeFalseIn(composite.getItemIterator());
        return false;
    }
    else if (composite instanceof NotItem || composite instanceof RankItem) { // collapse if first, remove otherwise
        ListIterator<Item> i = composite.getItemIterator();
        if (i.next() instanceof FalseItem) {
            parentIterator.set(new FalseItem());
            return true;
        }
        else {
            removeFalseIn(i);
            return false;
        }
    }
    else { // other composites not handled
        return false;
    }
}
 
Example 15
Source File: IndexDirectoryManager.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void replaceDirectory(final File oldIndexDir, final File newIndexDir, final boolean destroyOldIndex) {
    boolean replaced = false;

    synchronized (this) {
        for (final Map.Entry<Long, List<IndexLocation>> entry : indexLocationByTimestamp.entrySet()) {
            final List<IndexLocation> locations = entry.getValue();
            final ListIterator<IndexLocation> itr = locations.listIterator();

            while (itr.hasNext()) {
                final IndexLocation location = itr.next();
                if (location.getIndexDirectory().equals(oldIndexDir)) {
                    final IndexLocation updatedLocation = new IndexLocation(newIndexDir, location.getIndexStartTimestamp(), location.getPartitionName());
                    itr.set(updatedLocation);
                    replaced = true;
                    logger.debug("Replaced {} with {}", location, updatedLocation);
                }
            }
        }
    }

    if (!replaced) {
        insertIndexDirectory(newIndexDir);
    }

    if (destroyOldIndex) {
        try {
            FileUtils.deleteFile(oldIndexDir, true);
        } catch (IOException e) {
            logger.warn("Failed to delete index directory {}; this directory should be cleaned up manually", oldIndexDir, e);
        }
    }

    removeDirectory(oldIndexDir);

    logger.info("Successfully replaced old index directory {} with new index directory {}", oldIndexDir, newIndexDir);
}
 
Example 16
Source File: ToUpperCaseBuilder.java    From sequenceiq-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doProcess(Record record) {
    ListIterator iter = record.get(fieldName).listIterator();
    while (iter.hasNext()) {
        iter.set(transformFieldValue(iter.next()));
    }
    return super.doProcess(record);
}
 
Example 17
Source File: StreamingBuiltInFunctionTransformer.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public TupleFilter transform(TupleFilter tupleFilter) {
    TupleFilter translated = null;
    if (tupleFilter instanceof CompareTupleFilter) {
        //normal case
        translated = translateCompareTupleFilter((CompareTupleFilter) tupleFilter);
        if (translated != null) {
            logger.info("Translated {" + tupleFilter + "}");
        }
    } else if (tupleFilter instanceof BuiltInFunctionTupleFilter) {
        //like case
        translated = translateFunctionTupleFilter((BuiltInFunctionTupleFilter) tupleFilter);
        if (translated != null) {
            logger.info("Translated {" + tupleFilter + "}");
        }
    } else if (tupleFilter instanceof LogicalTupleFilter) {
        @SuppressWarnings("unchecked")
        ListIterator<TupleFilter> childIterator = (ListIterator<TupleFilter>) tupleFilter.getChildren()
                .listIterator();
        while (childIterator.hasNext()) {
            TupleFilter transformed = transform(childIterator.next());
            if (transformed != null)
                childIterator.set(transformed);
        }
    }

    TupleFilter result = translated == null ? tupleFilter : translated;
    if (result.getOperator() == TupleFilter.FilterOperatorEnum.NOT
            && !TupleFilter.isEvaluableRecursively(result)) {
        TupleFilter.collectColumns(result, unEvaluableColumns);
        return ConstantTupleFilter.TRUE;
    }

    // shortcut for unEvaluatable filter
    if (!result.isEvaluable()) {
        TupleFilter.collectColumns(result, unEvaluableColumns);
        return ConstantTupleFilter.TRUE;
    }
    return result;
}
 
Example 18
Source File: ReverseState.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked") // Safe casts assuming clone() works correctly
public Object clone() {
    try {
        ReverseState clonedState = (ReverseState) super.clone();

        /* clone checkers, if cloneable */
        clonedState.userCheckers =
                    (ArrayList<PKIXCertPathChecker>)userCheckers.clone();
        ListIterator<PKIXCertPathChecker> li =
                    clonedState.userCheckers.listIterator();
        while (li.hasNext()) {
            PKIXCertPathChecker checker = li.next();
            if (checker instanceof Cloneable) {
                li.set((PKIXCertPathChecker)checker.clone());
            }
        }

        /* make copy of name constraints */
        if (nc != null) {
            clonedState.nc = (NameConstraintsExtension) nc.clone();
        }

        /* make copy of policy tree */
        if (rootNode != null) {
            clonedState.rootNode = rootNode.copyTree();
        }

        return clonedState;
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e.toString(), e);
    }
}
 
Example 19
Source File: AbstractQueryModelNode.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected <T extends QueryModelNode> boolean replaceNodeInList(List<T> list, QueryModelNode current,
		QueryModelNode replacement) {
	ListIterator<T> iter = list.listIterator();
	while (iter.hasNext()) {
		if (iter.next() == current) {
			iter.set((T) replacement);
			replacement.setParentNode(this);
			return true;
		}
	}

	return false;
}
 
Example 20
Source File: MusicService.java    From Muzesto with GNU General Public License v3.0 4 votes vote down vote up
private int removeTracksInternal(int first, int last) {
    synchronized (this) {
        if (last < first) {
            return 0;
        } else if (first < 0) {
            first = 0;
        } else if (last >= mPlaylist.size()) {
            last = mPlaylist.size() - 1;
        }

        boolean gotonext = false;
        if (first <= mPlayPos && mPlayPos <= last) {
            mPlayPos = first;
            gotonext = true;
        } else if (mPlayPos > last) {
            mPlayPos -= last - first + 1;
        }
        final int numToRemove = last - first + 1;

        if (first == 0 && last == mPlaylist.size() - 1) {
            mPlayPos = -1;
            mNextPlayPos = -1;
            mPlaylist.clear();
            mHistory.clear();
        } else {
            for (int i = 0; i < numToRemove; i++) {
                mPlaylist.remove(first);
            }

            ListIterator<Integer> positionIterator = mHistory.listIterator();
            while (positionIterator.hasNext()) {
                int pos = positionIterator.next();
                if (pos >= first && pos <= last) {
                    positionIterator.remove();
                } else if (pos > last) {
                    positionIterator.set(pos - numToRemove);
                }
            }
        }
        if (gotonext) {
            if (mPlaylist.size() == 0) {
                stop(true);
                mPlayPos = -1;
                closeCursor();
            } else {
                if (mShuffleMode != SHUFFLE_NONE) {
                    mPlayPos = getNextPosition(true);
                } else if (mPlayPos >= mPlaylist.size()) {
                    mPlayPos = 0;
                }
                final boolean wasPlaying = isPlaying();
                stop(false);
                openCurrentAndNext();
                if (wasPlaying) {
                    play();
                }
            }
            notifyChange(META_CHANGED);
        }
        return last - first + 1;
    }
}