Java Code Examples for java.util.ArrayList#remove()

The following examples show how to use java.util.ArrayList#remove() . 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: MethodGenerator.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Remove the mapping from the name of the specified
 * {@link LocalVariableGen} to itself.
 * See also {@link #registerByName(LocalVariableGen)} and
 * {@link #lookUpByName(String)}
 * @param lvg a <code>LocalVariableGen</code>
 */
protected void removeByNameTracking(LocalVariableGen lvg) {
    Object duplicateNameEntry = _nameToLVGMap.get(lvg.getName());

    if (duplicateNameEntry instanceof ArrayList) {
        ArrayList sameNameList = (ArrayList) duplicateNameEntry;
        for (int i = 0; i < sameNameList.size(); i++) {
            if (sameNameList.get(i) == lvg) {
                sameNameList.remove(i);
                break;
            }
        }
    } else {
        _nameToLVGMap.remove(lvg);
    }
}
 
Example 2
Source File: TwitterUtils.java    From SmileEssence with MIT License 6 votes vote down vote up
/**
 * Get array of screenName in own text
 *
 * @param status            status
 * @param excludeScreenName
 * @return
 */
public static Collection<String> getScreenNames(Status status, String excludeScreenName) {
    ArrayList<String> names = new ArrayList<>();
    names.add(status.getUser().getScreenName());
    if (status.getUserMentionEntities() != null) {
        for (UserMentionEntity entity : status.getUserMentionEntities()) {
            if (names.contains(entity.getScreenName())) {
                continue;
            }
            names.add(entity.getScreenName());
        }
    }
    if (excludeScreenName != null) {
        names.remove(excludeScreenName);
    }
    return names;
}
 
Example 3
Source File: WordBank.java    From cannonball-android with Apache License 2.0 6 votes vote down vote up
private void shuffle() {
    // Adding same size random set of words in each group that will be reloaded
    // when user clicks Shuffle in the UI

    final int size = words.size();
    groupSize = size / MAX_WORDS_IN_GROUP;
    final Random random = new Random();
    currentGroup = 0;
    final ArrayList<String> clonedWords = (ArrayList<String>) words.clone();

    for (int i = 0; i < groupSize; i++) {
        groups.put(i, new ArrayList<String>());
    }

    for (int i = clonedWords.size(); i > 0; i--) {
        final int index = random.nextInt(i);

        final List<String> list = groups.get(currentGroup);
        list.add(clonedWords.get(index));
        clonedWords.remove(index);

        incrementCurrentGroup();
    }

    currentGroup = 0;
}
 
Example 4
Source File: EscapeAnalysis.java    From Box with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate through all the uses of a new object.
 *
 * @param result {@code non-null;} register where new object is stored
 * @param escSet {@code non-null;} EscapeSet for the new object
 */
private void processRegister(RegisterSpec result, EscapeSet escSet) {
    ArrayList<RegisterSpec> regWorklist = new ArrayList<RegisterSpec>();
    regWorklist.add(result);

    // Go through the worklist
    while (!regWorklist.isEmpty()) {
        int listSize = regWorklist.size() - 1;
        RegisterSpec def = regWorklist.remove(listSize);
        List<SsaInsn> useList = ssaMeth.getUseListForRegister(def.getReg());

        // Handle all the uses of this register
        for (SsaInsn use : useList) {
            Rop useOpcode = use.getOpcode();

            if (useOpcode == null) {
                // Handle phis
                processPhiUse(use, escSet, regWorklist);
            } else {
                // Handle other opcodes
                processUse(def, use, escSet, regWorklist);
            }
        }
    }
}
 
Example 5
Source File: VideoPanel.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Overrides DrawingPanel getDrawables method.
 *
 * @return a list of Drawable objects
 */
public ArrayList<Drawable> getDrawables() {
  ArrayList<Drawable> list = super.getDrawables();
  if(isDrawingInImageSpace()) {
    for(Drawable d : list) {
      if(!Trackable.class.isInstance(d)) {
        list.remove(d);
      }
    }
  }
  return list;
}
 
Example 6
Source File: CollectionBasedOHAddressCacheTestBase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testReleaseIdx0() {
  final GemFireCacheImpl gfc = createCache();
  final int BULK_SIZE = 16*1024;
  try {
    final int startOHObjects = getStats().getObjects();
    final CollectionBasedOHAddressCache c = createOHAddressCacheInstance();
    try {
      assertEquals(startOHObjects, getStats().getObjects());
      ArrayList<Long> expected = new ArrayList<Long>(BULK_SIZE);
      for (int i=0; i < BULK_SIZE; i++) {
        long addr = allocateSmallObject();
        c.put(addr);
        expected.add(0, addr);
        assertEquals(i+1, c.testHook_getSize());
        assertEquals(expected, c.testHook_copyToList());
      }
      for (int i=0; i < BULK_SIZE; i++) {
        c.releaseByteSource(0);
        expected.remove(0);
        assertEquals(BULK_SIZE-1-i, c.testHook_getSize());
        assertEquals(expected, c.testHook_copyToList());
      }
      assertEquals(startOHObjects, getStats().getObjects());
    } finally {
      c.release();
    }
  } finally {
    closeCache(gfc);
  }
}
 
Example 7
Source File: ThankYouWriter.java    From reladomo with Apache License 2.0 5 votes vote down vote up
void readdList(URL url, ArrayList requestList)
{
    // borisv per Moh's direction: technically requestList cannot be null, but in rear conditions, where JVM runs
    // out of memory, it can be null. Here is example:
    if (!this.done && requestList != null)
    {
        for (int i = 0; i < requestList.size(); )
        {
            RequestId requestId = (RequestId) requestList.get(i);
            if (requestId.isExpired())
            {
                requestList.remove(i);
            }
            else
            {
                i++;
            }
        }
        if (requestList.isEmpty())
        {
            return;
        }
        synchronized (this)
        {
            ArrayList list = (ArrayList) this.requestMap.get(url);
            if (list == null)
            {
                this.requestMap.put(url, requestList);
                this.notifyAll();
            }
            else
            {
                list.addAll(requestList);
            }
        }
    }
}
 
Example 8
Source File: TriggerHandler.java    From freeacs with MIT License 5 votes vote down vote up
private List<Trigger> createFilteredList(Trigger selectedTrigger) {
  ArrayList<Trigger> allTriggersList =
      new ArrayList<>(Arrays.asList(getUnittype().getTriggers().getTriggers()));
  allTriggersList.removeIf(trigger -> trigger.getTriggerType() == Trigger.TRIGGER_TYPE_BASIC);
  if (selectedTrigger == null) {
    return allTriggersList;
  }
  allTriggersList.remove(selectedTrigger);
  allTriggersList.removeAll(selectedTrigger.getAllChildren());
  return allTriggersList;
}
 
Example 9
Source File: PeripheralScannerTest.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void ensureGetFiltersIsShallow() {
    FitbitGatt.getInstance().resetScanFilters();
    FitbitGatt.getInstance().addDeviceAddressFilter("00:00:00:00:00:00");
    ArrayList<ScanFilter> filtersCopy = (ArrayList<ScanFilter>) FitbitGatt.getInstance().getScanFilters();
    filtersCopy.remove(0);
    assertTrue(filtersCopy.isEmpty());
    assertFalse(FitbitGatt.getInstance().getScanFilters().isEmpty());
}
 
Example 10
Source File: FetchShareListTask.java    From evercam-android with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected ArrayList<CameraShareInterface> doInBackground(Void... params) {
    ArrayList<CameraShareInterface> shareList = new ArrayList<>();

    try {
        shareList.addAll(CameraShare.getByCamera(cameraId));
        shareList.addAll(CameraShareRequest.get(cameraId, CameraShareRequest.STATUS_PENDING));

    } catch (EvercamException e) {
        Log.e(TAG, e.getMessage());
    }

    /**
     * Append the owner details as the first item in sharing list
     */
    if(shareList.size() > 0) {
        if(shareList.get(0) instanceof CameraShare) {
            CameraShareOwner owner = ((CameraShare) shareList.get(0)).getOwner();
            if(owner != null) {
                shareList.add(0, owner);
            }
        }
        CameraShare cameraShare =  ((CameraShare) shareList.get(1));

        if (cameraShare.toString().equals("{}")) {
            shareList.remove(1);
        }
    }
    return shareList;
}
 
Example 11
Source File: ATree.java    From ActivityTaskView with Apache License 2.0 5 votes vote down vote up
public void remove(String key, String value) {
    ArrayList<String> values = get(key);
    if(values == null) {
        return;
    }
    values.remove(value);
    if(values.isEmpty()) {
        remove(key);
    }

    lifeMap.remove(value);
}
 
Example 12
Source File: RecipeShapeless.java    From ProRecipes with GNU General Public License v2.0 5 votes vote down vote up
public boolean matchLowest(RecipeShapeless recipe){
	if(!match(recipe)){
		
		ArrayList<ItemStack> tt = new ArrayList<ItemStack>();
		tt.addAll(recipe.items);
		
		boolean contains = false;
		for(ItemStack i : items){
			contains = false;
			ItemStack latest = new ItemStack(Material.AIR);
			
			for(ItemStack p : tt){
				ItemStack out = i.clone();
				ItemStack in = p.clone();
				out.setAmount(1);
				in.setAmount(1);
				
				if(in.isSimilar(out)){
					if(i.getAmount() <= p.getAmount()){
						contains = true;
						latest = p;
						break;
					}else{
						contains = false;
						return false;
					}
				}
			}
			tt.remove(latest);
			
			if(!contains){
				return false;
			}
		}
		return contains;
	}else{
		return true;
	}
}
 
Example 13
Source File: SunFontManager.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void resolveFontFiles(HashSet<String> unmappedFiles,
                              ArrayList<String> unmappedFonts) {

    Locale l = SunToolkit.getStartupLocale();

    for (String file : unmappedFiles) {
        try {
            int fn = 0;
            TrueTypeFont ttf;
            String fullPath = getPathName(file);
            if (FontUtilities.isLogging()) {
                FontUtilities.getLogger()
                               .info("Trying to resolve file " + fullPath);
            }
            do {
                ttf = new TrueTypeFont(fullPath, null, fn++, false);
                //  prefer the font's locale name.
                String fontName = ttf.getFontName(l).toLowerCase();
                if (unmappedFonts.contains(fontName)) {
                    fontToFileMap.put(fontName, file);
                    unmappedFonts.remove(fontName);
                    if (FontUtilities.isLogging()) {
                        FontUtilities.getLogger()
                              .info("Resolved absent registry entry for " +
                                    fontName + " located in " + fullPath);
                    }
                }
            }
            while (fn < ttf.getFontCount());
        } catch (Exception e) {
        }
    }
}
 
Example 14
Source File: OVO.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
/**
 * It computes the confidence vector for the classes using the DDAG approach
 * @param example the example to be classified
 * @return the confidence vector
 */
protected String computeClassDDAG(double[] example)
{
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < nClasses; i++)
        list.add(new Integer(i));

    int clase;
    int x, y;
    int eliminado = -1;
    while (list.size() != 1)
    {
        /* Delete a class from the list in each iteration */
        for (int i = 0; i < list.size() - 1 && eliminado == -1; i++)
        {
            for (int j = list.size() - 1; j > i && eliminado == -1; j--)
            {
                x = list.get(i).intValue();
                y = list.get(j).intValue();
                clase = classifier.obtainClass(x, y, example);
                if (clase == x)
                    eliminado = list.remove(list.size() - 1);
                else if (clase == y)
                    eliminado = list.remove(0);
            }
        }
        /* If there is no class deleted, obtain the output class */
        if (eliminado == -1) {
            double[] max = new double[nClasses];
            for (int k = 1; k < nClasses; k++)
                if (list.contains(new Integer(k)))
                    max[k] = 1;
            return getOutputTies(max);
        }
        else
            eliminado = -1;
    }
    return classifier.train.getOutputValue(list.get(0));

}
 
Example 15
Source File: ShapelessOreRecipeTFC.java    From TFC2 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Used to check if a recipe matches current crafting inventory
 */
@Override
public boolean matches(NonNullList<ItemStack> var1, World world)
{
	ArrayList<Object> required = new ArrayList<Object>(input);

	for (int x = 0; x < var1.size(); x++)
	{
		ItemStack slot = var1.get(x);

		if (slot != ItemStack.EMPTY)
		{
			boolean inRecipe = false;
			Iterator<Object> req = required.iterator();

			while (req.hasNext())
			{
				boolean match = false;

				Object next = req.next();

				if (next instanceof ItemStack)
				{
					match = OreDictionary.itemMatches((ItemStack)next, slot, false);
				}
				else if (next instanceof List)
				{
					Iterator<ItemStack> itr = ((List<ItemStack>)next).iterator();
					while (itr.hasNext() && !match)
					{
						match = OreDictionary.itemMatches(itr.next(), slot, false);
					}
				}

				if (match)
				{
					if(!tempMatch(slot))
					{
						break;
					}
					inRecipe = true;
					required.remove(next);
					break;
				}


			}

			if (!inRecipe)
			{
				return false;
			}
		}
	}



	return required.isEmpty();
}
 
Example 16
Source File: AlarmManagerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
    if (operation == null && directReceiver == null) {
        if (localLOGV) {
            Slog.w(TAG, "requested remove() of null operation",
                    new RuntimeException("here"));
        }
        return;
    }

    boolean didRemove = false;
    final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
    for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
        Batch b = mAlarmBatches.get(i);
        didRemove |= b.remove(whichAlarms);
        if (b.size() == 0) {
            mAlarmBatches.remove(i);
        }
    }
    for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
        if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
            // Don't set didRemove, since this doesn't impact the scheduled alarms.
            mPendingWhileIdleAlarms.remove(i);
        }
    }
    for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
        final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
        for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
            if (alarmsForUid.get(j).matches(operation, directReceiver)) {
                // Don't set didRemove, since this doesn't impact the scheduled alarms.
                alarmsForUid.remove(j);
            }
        }
        if (alarmsForUid.size() == 0) {
            mPendingBackgroundAlarms.removeAt(i);
        }
    }
    if (didRemove) {
        if (DEBUG_BATCH) {
            Slog.v(TAG, "remove(operation) changed bounds; rebatching");
        }
        boolean restorePending = false;
        if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
            mPendingIdleUntil = null;
            restorePending = true;
        }
        if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
            mNextWakeFromIdle = null;
        }
        rebatchAllAlarmsLocked(true);
        if (restorePending) {
            restorePendingWhileIdleAlarmsLocked();
        }
        updateNextAlarmClockLocked();
    }
}
 
Example 17
Source File: mxGraphStructure.java    From blog-codes with Apache License 2.0 4 votes vote down vote up
/**
 * @param aGraph
 * @return true if the graph is connected
 */
public static boolean isConnected(mxAnalysisGraph aGraph)
{
	Object[] vertices = aGraph.getChildVertices(aGraph.getGraph().getDefaultParent());
	int vertexNum = vertices.length;

	if (vertexNum == 0)
	{
		throw new IllegalArgumentException();
	}

	//data preparation
	int connectedVertices = 1;
	int[] visited = new int[vertexNum];
	visited[0] = 1;

	for (int i = 1; i < vertexNum; i++)
	{
		visited[i] = 0;
	}

	ArrayList<Object> queue = new ArrayList<Object>();
	queue.add(vertices[0]);

	//repeat the algorithm until the queue is empty
	while (queue.size() > 0)
	{
		//cut out the first vertex
		Object currVertex = queue.get(0);
		queue.remove(0);

		//fill the queue with neighboring but unvisited vertexes
		Object[] neighborVertices = aGraph.getOpposites(aGraph.getEdges(currVertex, null, true, true, false, true), currVertex, true,
				true);

		for (int j = 0; j < neighborVertices.length; j++)
		{
			//get the index of the neighbor vertex
			int index = 0;

			for (int k = 0; k < vertexNum; k++)
			{
				if (vertices[k].equals(neighborVertices[j]))
				{
					index = k;
				}
			}

			if (visited[index] == 0)
			{
				queue.add(vertices[index]);
				visited[index] = 1;
				connectedVertices++;
			}
		}
	}

	// if we visited every vertex, the graph is connected
	if (connectedVertices == vertexNum)
	{
		return true;
	}
	else
	{
		return false;
	}
}
 
Example 18
Source File: ItemStatusHandler.java    From remixed-dungeon with GNU General Public License v3.0 4 votes vote down vote up
public ItemStatusHandler( Class<? extends T>[] items, Integer[] allImages ) {
	
	this.items = items;
	
	this.images = new HashMap<>();
	known       = new HashSet<>();
	
	ArrayList<Integer> imagesLeft = new ArrayList<>(Arrays.asList(allImages));
	
	for (int i=0; i < items.length; i++) {
		
		Class<? extends T> item = items[i];
		
		int index = Random.Int( imagesLeft.size() );

		images.put( item, imagesLeft.get( index ) );
		imagesLeft.remove( index );
	}
}
 
Example 19
Source File: SdkUpdaterLogic.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Find suitable updates to all current local packages.
 * <p/>
 * Returns a list of potential updates for *existing* packages. This does NOT solve
 * dependencies for the new packages.
 * <p/>
 * Always returns a non-null collection, which can be empty.
 */
private Collection<Archive> findUpdates(
        ArchiveInfo[] localArchives,
        Collection<Package> remotePkgs,
        SdkSource[] remoteSources,
        boolean includeAll) {
    ArrayList<Archive> updates = new ArrayList<Archive>();

    fetchRemotePackages(remotePkgs, remoteSources);

    for (ArchiveInfo ai : localArchives) {
        Archive na = ai.getNewArchive();
        if (na == null) {
            continue;
        }
        Package localPkg = na.getParentPackage();

        for (Package remotePkg : remotePkgs) {
            // Only look for non-obsolete updates unless requested to include them
            if ((includeAll || !remotePkg.isObsolete()) &&
                    localPkg.canBeUpdatedBy(remotePkg) == UpdateInfo.UPDATE) {
                // Found a suitable update. Only accept the remote package
                // if it provides at least one compatible archive

                addArchives:
                for (Archive a : remotePkg.getArchives()) {
                    if (a.isCompatible()) {

                        // If we're trying to add a package for revision N,
                        // make sure we don't also have a package for revision N-1.
                        for (int i = updates.size() - 1; i >= 0; i--) {
                            Package pkgFound = updates.get(i).getParentPackage();
                            if (pkgFound.canBeUpdatedBy(remotePkg) == UpdateInfo.UPDATE) {
                                // This package can update one we selected earlier.
                                // Remove the one that can be updated by this new one.
                               updates.remove(i);
                            } else if (remotePkg.canBeUpdatedBy(pkgFound) ==
                                            UpdateInfo.UPDATE) {
                                // There is a package in the list that is already better
                                // than the one we want to add, so don't add it.
                                break addArchives;
                            }
                        }

                        updates.add(a);
                        break;
                    }
                }
            }
        }
    }

    return updates;
}
 
Example 20
Source File: ChunkLoadHandler.java    From TFC2 with GNU General Public License v3.0 4 votes vote down vote up
@SubscribeEvent
public void onChunkUnload(ChunkEvent.Unload event)
{
	if(!event.getWorld().isRemote && event.getWorld().provider.getDimension() == 0)
	{
		BlockPos chunkWorldPos = new BlockPos(event.getChunk().xPosition * 16, 0, event.getChunk().zPosition * 16);
		IslandMap map = Core.getMapForWorld(event.getWorld(), chunkWorldPos);

		Point islandPos = new Point(chunkWorldPos.getX(), chunkWorldPos.getZ()).toIslandCoord();
		AxisAlignedBB chunkAABB = new AxisAlignedBB(islandPos.getX(), 0, islandPos.getZ(), islandPos.getX()+16, 1, islandPos.getZ()+16);
		Center temp = map.getClosestCenter(islandPos);

		ArrayList<Center> genList = new ArrayList<Center>();
		genList.add(temp);
		genList.addAll(temp.neighbors);

		if(loadedCentersMap.containsKey(map.getParams().getCantorizedID()))
		{
			ArrayList<Center> loaded = loadedCentersMap.get(map.getParams().getCantorizedID());
			for(Center c : genList)
			{	
				AxisAlignedBB aabb = c.getAABB();
				boolean intersect =aabb.intersectsWith(chunkAABB);
				if(intersect && loaded.contains(c) )
				{
					loaded.remove(c);
					ArrayList<Herd> herdsToUnload = map.getIslandData().wildlifeManager.getHerdsInCenter(c);
					for(Herd h : herdsToUnload)
					{
						h.setUnloaded();
						for(VirtualAnimal animal : h.getVirtualAnimals())
						{
							if(animal.getEntity() == null)
							{
								animal.setUnloaded();
								continue;
							}
							Predicate<Entity> predicate = Predicates.<Entity>and(EntitySelectors.NOT_SPECTATING, EntitySelectors.notRiding(animal.getEntity()));
							Entity closestEntity = animal.getEntity().world.getClosestPlayer(animal.getEntity().posX, animal.getEntity().posY, animal.getEntity().posZ, 100D, predicate);
							if(closestEntity == null)
							{
								animal.getEntity().setDead();
								animal.setUnloaded();
							}
						}
					}
				}
			}
		}


	}
}