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

The following examples show how to use java.util.ListIterator#add() . 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: Group.java    From JavaSkype with MIT License 8 votes vote down vote up
/**
 * Changes the role of a user in this group. Group admin rights are needed.
 *
 * @param user The user whose role is to be changed
 * @param role The new role of the user.
 * @return true if the Skype account has admin rights, and the user was in the group and didn't have this role already.
 * @see #isSelfAdmin()
 */
public boolean changeUserRole(User user, Role role) {
  if (!isSelfAdmin()) {
    return false;
  }
  // we need to make sure the user is in the group to avoid getting an error
  ListIterator<Pair<User, Role>> it = users.listIterator();
  while (it.hasNext()) {
    Pair<User, Role> pair = it.next();
    if (user.equals(pair.getFirst())) {
      // need to return if it already has the same role to avoid getting an error
      if (role == pair.getSecond()) {
        return false;
      }
      it.remove();
      it.add(new Pair<>(user, role));
      skype.changeUserRole(user, role, this);
      return true;
    }
  }
  return false;
}
 
Example 2
Source File: AuthCacheImpl.java    From hottub with GNU General Public License v2.0 8 votes vote down vote up
public synchronized void put (String pkey, AuthCacheValue value) {
    LinkedList<AuthCacheValue> list = hashtable.get (pkey);
    String skey = value.getPath();
    if (list == null) {
        list = new LinkedList<AuthCacheValue>();
        hashtable.put(pkey, list);
    }
    // Check if the path already exists or a super-set of it exists
    ListIterator<AuthCacheValue> iter = list.listIterator();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (inf.path == null || inf.path.startsWith (skey)) {
            iter.remove ();
        }
    }
    iter.add(value);
}
 
Example 3
Source File: AuthCacheImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public synchronized void put (String pkey, AuthCacheValue value) {
    LinkedList<AuthCacheValue> list = hashtable.get (pkey);
    String skey = value.getPath();
    if (list == null) {
        list = new LinkedList<AuthCacheValue>();
        hashtable.put(pkey, list);
    }
    // Check if the path already exists or a super-set of it exists
    ListIterator<AuthCacheValue> iter = list.listIterator();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (inf.path == null || inf.path.startsWith (skey)) {
            iter.remove ();
        }
    }
    iter.add(value);
}
 
Example 4
Source File: AbstractRowTimeUnboundedPrecedingOver.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts timestamps in order into a linked list.
 * If timestamps arrive in order (as in case of using the RocksDB state backend) this is just
 * an append with O(1).
 */
private void insertToSortedList(Long recordTimestamp) {
	ListIterator<Long> listIterator = sortedTimestamps.listIterator(sortedTimestamps.size());
	boolean isContinue = true;
	while (listIterator.hasPrevious() && isContinue) {
		Long timestamp = listIterator.previous();
		if (recordTimestamp >= timestamp) {
			listIterator.next();
			listIterator.add(recordTimestamp);
			isContinue = false;
		}
	}

	if (isContinue) {
		sortedTimestamps.addFirst(recordTimestamp);
	}
}
 
Example 5
Source File: AttributeMapper.java    From MyVirtualDirectory with Apache License 2.0 6 votes vote down vote up
public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException {
	
	ListIterator<LDAPModification> it = mods.listIterator();
	while (it.hasNext()) {
		LDAPModification mod = it.next();
		String newName = this.localMap.get(mod.getAttribute().getBaseName().toLowerCase());
		if (newName != null) {
			LDAPAttribute newAttrib = new LDAPAttribute(newName);
			byte[][] vals = mod.getAttribute().getByteValueArray();
			for (int i=0,m=vals.length;i<m;i++) {
				newAttrib.addValue(vals[i]);
			}
			LDAPModification newMod = new LDAPModification(mod.getOp(),newAttrib);
			it.remove();
			it.add(newMod);
		}
	}
	
	chain.nextModify(dn,mods,constraints);
	
}
 
Example 6
Source File: AbstractJavaCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
    // recursively add import for mapping one type to multiple imports
    List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
    if (recursiveImports == null)
        return objs;

    ListIterator<Map<String, String>> listIterator = recursiveImports.listIterator();
    while (listIterator.hasNext()) {
        String _import = listIterator.next().get("import");
        // if the import package happens to be found in the importMapping (key)
        // add the corresponding import package to the list
        if (importMapping.containsKey(_import)) {
            Map<String, String> newImportMap= new HashMap<String, String>();
            newImportMap.put("import", importMapping.get(_import));
            listIterator.add(newImportMap);
        }
    }

    return postProcessModelsEnum(objs);
}
 
Example 7
Source File: ASMHelper.java    From jaop with Apache License 2.0 6 votes vote down vote up
public static void returnNode(ListIterator<AbstractInsnNode> iterator, String paramType) {
    //(Ljava/lang/String;IDCBSJZF)V
    if ("I".equals(paramType)
            || "C".equals(paramType)
            || "B".equals(paramType)
            || "S".equals(paramType)
            || "Z".equals(paramType)
            ) {
        iterator.add(new InsnNode(Opcodes.IRETURN));
    } else if ("J".equals(paramType)) {
        iterator.add(new InsnNode(Opcodes.LRETURN));
    } else if ("F".equals(paramType)) {
        iterator.add(new InsnNode(Opcodes.FRETURN));
    } else if ("D".equals(paramType)) {
        iterator.add(new InsnNode(Opcodes.DRETURN));
    } else if ("V".equals(paramType)) {
        iterator.add(new InsnNode(Opcodes.RETURN));
    } else {
        iterator.add(new InsnNode(Opcodes.ARETURN));
    }
}
 
Example 8
Source File: TextTrieMap.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void add(char[] text, int offset, V value) {
    if (text.length == offset) {
        _values = addValue(_values, value);
        return;
    }

    if (_children == null) {
        _children = new LinkedList<Node>();
        Node child = new Node(subArray(text, offset), addValue(null, value), null);
        _children.add(child);
        return;
    }

    // walk through children
    ListIterator<Node> litr = _children.listIterator();
    while (litr.hasNext()) {
        Node next = litr.next();
        if (text[offset] < next._text[0]) {
            litr.previous();
            break;
        }
        if (text[offset] == next._text[0]) {
            int matchLen = next.lenMatches(text, offset);
            if (matchLen == next._text.length) {
                // full match
                next.add(text, offset + matchLen, value);
            } else {
                // partial match, create a branch
                next.split(matchLen);
                next.add(text, offset + matchLen, value);
            }
            return;
        }
    }
    // add a new child to this node
    litr.add(new Node(subArray(text, offset), addValue(null, value), null));
}
 
Example 9
Source File: VectorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_listIterator_addAndPrevious() {
    ListIterator<String> it = new Vector<String>().listIterator();
    assertFalse(it.hasNext());
    it.add("value");
    assertEquals("value", it.previous());
    assertTrue(it.hasNext());
}
 
Example 10
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 11
Source File: ItemsCommonStuffTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public final void testIteratorJuggling() {
    AndItem a = new AndItem();
    WordItem w0 = new WordItem("nalle");
    WordItem w1 = new WordItem("bamse");
    WordItem w2 = new WordItem("teddy");
    boolean caught = false;
    a.addItem(w0);
    a.addItem(w1);
    ListIterator<Item> i = a.getItemIterator();
    assertFalse(i.hasPrevious());
    try {
        i.previous();
    } catch (NoSuchElementException e) {
        caught = true;
    }
    assertTrue(caught);
    assertEquals(-1, i.previousIndex());
    assertEquals(0, i.nextIndex());
    i.next();
    WordItem wn = (WordItem) i.next();
    assertSame(w1, wn);
    assertSame(w1, i.previous());
    assertSame(w0, i.previous());
    assertEquals(0, i.nextIndex());
    i.add(w2);
    assertEquals(1, i.nextIndex());
}
 
Example 12
Source File: ASMHelper.java    From jaop with Apache License 2.0 5 votes vote down vote up
public static void intInsnNode(ListIterator<AbstractInsnNode> iterator, int i) {
        if (i >=0 && i < 6) {
//            int ICONST_0 = 3; // -
//            int ICONST_1 = 4; // -
//            int ICONST_2 = 5; // -
//            int ICONST_3 = 6; // -
//            int ICONST_4 = 7; // -
//            int ICONST_5 = 8; // -
            iterator.add(new InsnNode(Opcodes.ICONST_0 + i));
        } else {
            iterator.add(new IntInsnNode(Opcodes.BIPUSH, i));
        }
    }
 
Example 13
Source File: CommandInjection.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String transferListIteratorIndirect(String str) {
    List<String> list = new LinkedList<String>();
    // not able to transfer this, set as UNKNOWN even if str is SAFE
    ListIterator<String> listIterator = list.listIterator();
    listIterator.add(str);
    return list.get(0);
}
 
Example 14
Source File: PhaseController.java    From Cardshifter with Apache License 2.0 5 votes vote down vote up
public boolean insertTemporaryPhaseAfter(Phase phase, Predicate<Phase> afterPhase) {
	ListIterator<Phase> it = navigateToRecreate(afterPhase);
	if (it != null) {
		it.add(phase);
	}
	return it != null;
}
 
Example 15
Source File: ListEnvelopeTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void subListReturnsListIteratorWithUnsupportedAdd() {
    final ListEnvelope<String> list = new StringList("one");
    final ListIterator<String> iterator = list.subList(0, 1)
        .listIterator();
    iterator.next();
    iterator.add("two");
}
 
Example 16
Source File: RangeSetImpl.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public void subtract(final RangeSet other)
{
    final Iterator<Range> otherIter = other.iterator() ;
    if (otherIter.hasNext())
    {
        Range otherRange = otherIter.next();
        final ListIterator<Range> iter = ranges.listIterator() ;
        if (iter.hasNext())
        {
            Range range = iter.next();
            do
            {
                if (otherRange.getUpper() < range.getLower())
                {
                    otherRange = nextRange(otherIter) ;
                }
                else if (range.getUpper() < otherRange.getLower())
                {
                    range = nextRange(iter) ;
                }
                else
                {
                    final boolean first = range.getLower() < otherRange.getLower() ;
                    final boolean second = otherRange.getUpper() < range.getUpper() ;

                    if (first)
                    {
                        iter.set(Range.newInstance(range.getLower(), otherRange.getLower()-1)) ;
                        if (second)
                        {
                            iter.add(Range.newInstance(otherRange.getUpper()+1, range.getUpper())) ;
                            iter.previous() ;
                            range = iter.next() ;
                        }
                        else
                        {
                            range = nextRange(iter) ;
                        }
                    }
                    else if (second)
                    {
                        range = Range.newInstance(otherRange.getUpper()+1, range.getUpper()) ;
                        iter.set(range) ;
                        otherRange = nextRange(otherIter) ;
                    }
                    else
                    {
                        iter.remove() ;
                        range = nextRange(iter) ;
                    }
                }
            }
            while ((otherRange != null) && (range != null)) ;
        }
    }
}
 
Example 17
Source File: DiffMatchPatch.java    From titan-hotfix with Apache License 2.0 4 votes vote down vote up
/**
 * Do a quick line-level diff on both strings, then rediff the parts for
 * greater accuracy.
 * This speedup can produce non-minimal diffs.
 *
 * @param text1    Old string to be diffed.
 * @param text2    New string to be diffed.
 * @param deadline Time when the diff should be complete by.
 * @return Linked List of Diff objects.
 */
private LinkedList<Diff> diffLineMode(String text1, String text2,
                                      long deadline) {
    // Scan the text on a line-by-line basis first.
    LinesToCharsResult a = diffLinesToChars(text1, text2);
    text1 = a.chars1;
    text2 = a.chars2;
    List<String> linearray = a.lineArray;

    LinkedList<Diff> diffs = diffMain(text1, text2, false, deadline);

    // Convert the diff back to original text.
    diffCharsToLines(diffs, linearray);
    // Eliminate freak matches (e.g. blank lines)
    diffCleanupSemantic(diffs);

    // Rediff any replacement blocks, this time character-by-character.
    // Add a dummy entry at the end.
    diffs.add(new Diff(Operation.EQUAL, ""));
    int countDelete = 0;
    int countInsert = 0;
    String textDelete = "";
    String textInsert = "";
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff thisDiff = pointer.next();
    while (thisDiff != null) {
        switch (thisDiff.operation) {
            case INSERT:
                countInsert++;
                textInsert += thisDiff.text;
                break;
            case DELETE:
                countDelete++;
                textDelete += thisDiff.text;
                break;
            case EQUAL:
                // Upon reaching an equality, check for prior redundancies.
                if (countDelete >= 1 && countInsert >= 1) {
                    // Delete the offending records and add the merged ones.
                    pointer.previous();
                    for (int j = 0; j < countDelete + countInsert; j++) {
                        pointer.previous();
                        pointer.remove();
                    }
                    for (Diff subDiff : diffMain(textDelete, textInsert, false,
                            deadline)) {
                        pointer.add(subDiff);
                    }
                }
                countInsert = 0;
                countDelete = 0;
                textDelete = "";
                textInsert = "";
                break;
            default:
                throw new RuntimeException();
        }
        thisDiff = pointer.hasNext() ? pointer.next() : null;
    }
    diffs.removeLast();  // Remove the dummy entry at the end.

    return diffs;
}
 
Example 18
Source File: TextDiffMatcher.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Do a quick line-level diff on both strings, then rediff the parts for
 * greater accuracy.
 * This speedup can produce non-minimal diffs.
 * @param text1 Old string to be diffed.
 * @param text2 New string to be diffed.
 * @param deadline Time when the diff should be complete by.
 * @return Linked List of Diff objects.
 */
private LinkedList<Diff> diff_lineMode(String text1, String text2,
                                       long deadline) {
  // Scan the text on a line-by-line basis first.
  LinesToCharsResult b = diff_linesToChars(text1, text2);
  text1 = b.chars1;
  text2 = b.chars2;
  List<String> linearray = b.lineArray;

  LinkedList<Diff> diffs = diff_main(text1, text2, false, deadline);

  // Convert the diff back to original text.
  diff_charsToLines(diffs, linearray);
  // Eliminate freak matches (e.g. blank lines)
  diff_cleanupSemantic(diffs);

  // Rediff any replacement blocks, this time character-by-character.
  // Add a dummy entry at the end.
  diffs.add(new Diff(Operation.EQUAL, ""));
  int count_delete = 0;
  int count_insert = 0;
  String text_delete = "";
  String text_insert = "";
  ListIterator<Diff> pointer = diffs.listIterator();
  Diff thisDiff = pointer.next();
  while (thisDiff != null) {
    switch (thisDiff.operation) {
    case INSERT:
      count_insert++;
      text_insert += thisDiff.text;
      break;
    case DELETE:
      count_delete++;
      text_delete += thisDiff.text;
      break;
    case EQUAL:
      // Upon reaching an equality, check for prior redundancies.
      if (count_delete >= 1 && count_insert >= 1) {
        // Delete the offending records and add the merged ones.
        pointer.previous();
        for (int j = 0; j < count_delete + count_insert; j++) {
          pointer.previous();
          pointer.remove();
        }
        for (Diff newDiff : diff_main(text_delete, text_insert, false,
            deadline)) {
          pointer.add(newDiff);
        }
      }
      count_insert = 0;
      count_delete = 0;
      text_delete = "";
      text_insert = "";
      break;
    }
    thisDiff = pointer.hasNext() ? pointer.next() : null;
  }
  diffs.removeLast();  // Remove the dummy entry at the end.

  return diffs;
}
 
Example 19
Source File: SolidListTest.java    From solid with MIT License 4 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testListIteratorAddThrows() throws Exception {
    ListIterator<Integer> iterator = new SolidList<>(Collections.singletonList(0)).listIterator();
    iterator.next();
    iterator.add(0);
}
 
Example 20
Source File: Segment.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @deprecated
 * the parameter left and right should be equal, or the LEFT_MOST_EDGE and the RIGHT_MOST_EDGE 
 * @param left
 * @param right
 */
void insertSection( Object left, Object right )
{
	// drop the normalize result
	sections = null;
	SegmentEdge edge = null;

	if ( left == Segment.LEFT_MOST_EDGE && right == Segment.RIGHT_MOST_EDGE )
	{
		while ( edges.size( ) > 0 )
		{
			edges.remove( );
		}
		edge = new SegmentEdge( left, true );
		edges.add( edge );
		edge = new SegmentEdge( right, false );
		edges.add( edge );
		return;
	}

	if ( left != right )
	{
		return;
	}
	// try to find the first segment will less that left
	ListIterator iter = edges.listIterator( edges.size( ) );
	while ( iter.hasPrevious( ) )
	{
		SegmentEdge next = (SegmentEdge) iter.previous( );
		if ( comparator.compare( next.offset, left ) <= 0 )
		{
			// insert it after the next
			if ( !next.leftEdge )
			{
				iter.next( );
				edge = new SegmentEdge( left, true );
				iter.add( edge );
				edge = new SegmentEdge( right, false );
				iter.add( edge );
			}
			return;
		}
	}
	if ( edge == null )
	{
		// insert it at the end of the list
		edge = new SegmentEdge( right, false );
		edges.addFirst( edge );
		edge = new SegmentEdge( left, true );
		edges.addFirst( edge );
	}
}