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

The following are Jave code examples for showing how to use remove() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: VASSAL-src   File: MapBoard.java   View Source Code Vote up 6 votes
void drawLines(Graphics2D g, int cap) {
  final ArrayList<LineDefinition> lds =
    new ArrayList<LineDefinition>(Arrays.asList(lineDefinitions));

  // find the next line in priority
  while (lds.size() > 0) {
    LineDefinition lowest = null;
    for (LineDefinition ld : lds) {
      if (ld == null)
        continue;
      else if (lowest == null || compare(ld, lowest) < 0)
        lowest = ld;
    }
    if (lowest == null)
      break;
    else {
      lowest.draw(g, cap);
      lowest.clearPoints();
      lds.remove(lowest);
    }
  }
}
 
Example 2
Project: FlickLauncher   File: Launcher.java   View Source Code Vote up 6 votes
@Override
public void bindScreens(ArrayList<Long> orderedScreenIds) {
    // Make sure the first screen is always at the start.
    if (FeatureFlags.QSB_ON_FIRST_SCREEN &&
            orderedScreenIds.indexOf(Workspace.FIRST_SCREEN_ID) != 0) {
        orderedScreenIds.remove(Workspace.FIRST_SCREEN_ID);
        orderedScreenIds.add(0, Workspace.FIRST_SCREEN_ID);
        mModel.updateWorkspaceScreenOrder(this, orderedScreenIds);
    } else if (!FeatureFlags.QSB_ON_FIRST_SCREEN && orderedScreenIds.isEmpty()) {
        // If there are no screens, we need to have an empty screen
        mWorkspace.addExtraEmptyScreen();
    }
    bindAddScreens(orderedScreenIds);

    // Create the custom content page (this call updates mDefaultScreen which calls
    // setCurrentPage() so ensure that all pages are added before calling this).
    if (hasCustomContentToLeft()) {
        mWorkspace.createCustomContentContainer();
        populateCustomContentContainer();
    }

    // After we have added all the screens, if the wallpaper was locked to the default state,
    // then notify to indicate that it can be released and a proper wallpaper offset can be
    // computed before the next layout
    mWorkspace.unlockWallpaperFromDefaultPageOnNextLayout();
}
 
Example 3
Project: PlusGram   File: MediaController.java   View Source Code Vote up 6 votes
private void buildShuffledPlayList() {
    if (playlist.isEmpty()) {
        return;
    }
    ArrayList<MessageObject> all = new ArrayList<>(playlist);
    shuffledPlaylist.clear();

    MessageObject messageObject = playlist.get(currentPlaylistNum);
    all.remove(currentPlaylistNum);
    shuffledPlaylist.add(messageObject);

    int count = all.size();
    for (int a = 0; a < count; a++) {
        int index = Utilities.random.nextInt(all.size());
        shuffledPlaylist.add(all.get(index));
        all.remove(index);
    }
}
 
Example 4
Project: openjdk-jdk10   File: PrintServiceLookupProvider.java   View Source Code Vote up 6 votes
private int addPrintServiceToList(ArrayList<PrintService> printerList, PrintService ps) {
    int index = printerList.indexOf(ps);
    // Check if PrintService with same name is already in the list.
    if (CUPSPrinter.isCupsRunning() && index != -1) {
        // Bug in Linux: Duplicate entry of a remote printer
        // and treats it as local printer but it is returning wrong
        // information when queried using IPP. Workaround is to remove it.
        // Even CUPS ignores these entries as shown in lpstat or using
        // their web configuration.
        PrinterURI uri = ps.getAttribute(PrinterURI.class);
        if (uri.getURI().getHost().equals("localhost")) {
            IPPPrintService.debug_println(debugPrefix+"duplicate PrintService, ignoring the new local printer: "+ps);
            return index;  // Do not add this.
        }
        PrintService oldPS = printerList.get(index);
        uri = oldPS.getAttribute(PrinterURI.class);
        if (uri.getURI().getHost().equals("localhost")) {
            IPPPrintService.debug_println(debugPrefix+"duplicate PrintService, removing existing local printer: "+oldPS);
            printerList.remove(oldPS);
        } else {
            return index;
        }
    }
    printerList.add(ps);
    return (printerList.size() - 1);
}
 
Example 5
Project: JavaRushTasks   File: Solution.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    //напишите тут ваш код
    ArrayList<String> list = new ArrayList<String>();

    Scanner sc = new Scanner(System.in);


    for (int i = 0; i < 5; i++) {
        list.add(sc.nextLine());
    }

    String tmp;
    for (int i = 0; i < 13; i++) {
        tmp = list.get(list.size()-1);
        list.add(0,tmp);
        list.remove(list.size()-1);
    }



    for (int i = 0; i < 5; i++) {
        System.out.println(list.get(i));
    }
}
 
Example 6
Project: BiglyBT   File: IncomingMessageQueueImpl.java   View Source Code Vote up 5 votes
/**
 * Cancel queue event notification listener.
 * @param listener
 */
@Override
public void cancelQueueListener(MessageQueueListener listener ) {
  try{  listeners_mon.enter();
    //copy-on-write
    ArrayList new_list = new ArrayList( listeners );
    new_list.remove( listener );
    listeners = new_list;
  }
  finally{  listeners_mon.exit();  }
}
 
Example 7
Project: Scheduler-Marwa-slafa-FEHIM-Mahfoud-   File: Scheduler.java   View Source Code Vote up 5 votes
public ArrayList<Processus> Fin_Exe_proc(ArrayList<Processus> list_pro_Exe, String algo, int time) {
    if (time_Exe_proc == 0) {  // condiiton ajouter du a un problem de simulation car programme il faut que exe il n'a pas 
        //intelligence car quand P1 sort terminer  est subtiment P2 arrive cette condition regle se problem dans la boucle  while au Fin  Exe pro est appeller 
        switch (algo) {
            case "FCFS":
                list_pro_Exe.get(0).setTempFin(time);

                fenetre_execute.add_Exe_Table(list_pro_Exe.get(0).getNomPre(), "", String.valueOf(list_pro_Exe.get(0).getTempFin()), "Terminer");
                fenetre_execute.add_diagramme(list_pro_Exe.get(max).getNomPre(), 0, time);
                list_pro_Exe.remove(0);

                break;

            case "SJF":

                list_pro_Exe.get(min).setTempFin(time);
                fenetre_execute.add_Exe_Table(list_pro_Exe.get(min).getNomPre(), "", String.valueOf(list_pro_Exe.get(min).getTempFin()), "Terminer");
                fenetre_execute.add_diagramme(list_pro_Exe.get(max).getNomPre(), 0, time);
                list_pro_Exe.remove(min);
                break;

            case "Priority":
                list_pro_Exe.get(max).setTempFin(time); // initialiser temp fin de processus terminer
                fenetre_execute.add_Exe_Table(list_pro_Exe.get(max).getNomPre(), "", String.valueOf(list_pro_Exe.get(max).getTempFin()), "Terminer");
                fenetre_execute.add_diagramme(list_pro_Exe.get(max).getNomPre(), 0, time);
                list_pro_Exe.remove(max); // elever processus de la liste

                break;

        }
    }

    return list_pro_Exe;
}
 
Example 8
Project: localcloud_fe   File: Filesystem.java   View Source Code Vote up 5 votes
/**
 * Removes multiple repeated //s, and collapses processes ../s.
 */
protected static String normalizePath(String rawPath) {
    // If this is an absolute path, trim the leading "/" and replace it later
    boolean isAbsolutePath = rawPath.startsWith("/");
    if (isAbsolutePath) {
        rawPath = rawPath.replaceFirst("/+", "");
    }
    ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/+")));
    for (int index = 0; index < components.size(); ++index) {
        if (components.get(index).equals("..")) {
            components.remove(index);
            if (index > 0) {
                components.remove(index-1);
                --index;
            }
        }
    }
    StringBuilder normalizedPath = new StringBuilder();
    for(String component: components) {
        normalizedPath.append("/");
        normalizedPath.append(component);
    }
    if (isAbsolutePath) {
        return normalizedPath.toString();
    } else {
        return normalizedPath.toString().substring(1);
    }
}
 
Example 9
Project: airgram   File: LruCache.java   View Source Code Vote up 5 votes
/**
 * Removes the entry for {@code key} if it exists.
 *
 * @return the previous value mapped by {@code key}.
 */
public final BitmapDrawable remove(String key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

    BitmapDrawable previous;
    synchronized (this) {
        previous = map.remove(key);
        if (previous != null) {
            size -= safeSizeOf(key, previous);
        }
    }

    if (previous != null) {
        String[] args = key.split("@");
        if (args.length > 1) {
            ArrayList<String> arr = mapFilters.get(args[0]);
            if (arr != null) {
                arr.remove(args[1]);
                if (arr.isEmpty()) {
                    mapFilters.remove(args[0]);
                }
            }
        }

        entryRemoved(false, key, previous, null);
    }

    return previous;
}
 
Example 10
Project: peersim-pcbroadcast   File: PartialView.java   View Source Code Vote up 5 votes
public Iterable<Node> getPeers(int k) {
	if (this.partialView.size() == k || k == Integer.MAX_VALUE) {
		return this.getPeers();
	} else {
		HashBag<Node> sample = new HashBag<Node>();
		ArrayList<Node> clone = new ArrayList<Node>(this.partialView);
		while (sample.size() < Math.min(k, this.partialView.size())) {
			int rn = CommonState.r.nextInt(clone.size());
			sample.add(clone.get(rn));
			clone.remove(rn);
		}
		return sample;
	}
}
 
Example 11
Project: PlusGram   File: LruCache.java   View Source Code Vote up 5 votes
/**
 * Removes the entry for {@code key} if it exists.
 *
 * @return the previous value mapped by {@code key}.
 */
public final BitmapDrawable remove(String key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

    BitmapDrawable previous;
    synchronized (this) {
        previous = map.remove(key);
        if (previous != null) {
            size -= safeSizeOf(key, previous);
        }
    }

    if (previous != null) {
        String[] args = key.split("@");
        if (args.length > 1) {
            ArrayList<String> arr = mapFilters.get(args[0]);
            if (arr != null) {
                arr.remove(args[1]);
                if (arr.isEmpty()) {
                    mapFilters.remove(args[0]);
                }
            }
        }

        entryRemoved(false, key, previous, null);
    }

    return previous;
}
 
Example 12
Project: ShotsNewsApp   File: VerticalCycleAdapter.java   View Source Code Vote up 5 votes
public VerticalCycleAdapter(Context context)
{
    this.context=context;
    sharedPreferences=context.getSharedPreferences("MYSHAREDPREFERENCES",MODE_PRIVATE);
    String mip=sharedPreferences.getString("mip","lol");
    String interests=sharedPreferences.getString("interests","lol");
    String mydomain=sharedPreferences.getString("mydomain","Nodomain");
    ArrayList<String> my_interests=new ArrayList<>();
    StringTokenizer st1=new StringTokenizer(interests,",");
    if(mydomain.equals("null"))
    {
        mydomain="Programming";
    }
    my_interests.add(mydomain);
    while (st1.hasMoreTokens())
    {
        String token=st1.nextToken();
        my_interests.add(token);
    }

    my_interests.remove("Tech");
    for(int i=0;i<NewsPOGO.newsArray.size();i++)
    {
        String types=NewsPOGO.newsArray.get(i).types;
        for(int j=0;j<my_interests.size();j++)
        if(NewsPOGO.newsArray.get(i).types.contains(my_interests.get(j)))
        {
            filteredNews.add(NewsPOGO.newsArray.get(i));
            Log.d("interests", "VerticalCycleAdapter: "+my_interests.get(j)+"  "+NewsPOGO.newsArray.get(i).body.substring(0,20));
            break;
        }
    }
}
 
Example 13
Project: JkImageLoader   File: StringUtils.java   View Source Code Vote up 5 votes
/**
 * two items in a list of data exchange
 * @author leibing
 * @createTime 2016/12/3
 * @lastModify 2016/12/3
 * @param mList
 * @param swapNum1
 * @param swapNum2
 * @return
 */
public static void listSwapItem(ArrayList mList, int swapNum1, int swapNum2){
	// if no data,just return it
	if (mList == null || mList.size() == 0)
		return;
	// if the index cross-border,just return it
	if (swapNum1 >= mList.size() || swapNum2 >= mList.size())
		return;
	// swap data manipulation
	mList.add(swapNum1, mList.get(swapNum2));
	mList.add(swapNum2 + 1, mList.get(swapNum1 + 1));
	mList.remove(swapNum1 + 1);
	mList.remove(swapNum2 + 1);
}
 
Example 14
Project: javaide   File: Dominators.java   View Source Code Vote up 5 votes
/**
 * Performs path compress on the DFS info.
 *
 * @param in Basic block whose DFS info we are path compressing.
 */
private void compress(SsaBasicBlock in) {
    DFSInfo bbInfo = info[in.getIndex()];
    DFSInfo ancestorbbInfo = info[bbInfo.ancestor.getIndex()];

    if (ancestorbbInfo.ancestor != null) {
        ArrayList<SsaBasicBlock> worklist = new ArrayList<SsaBasicBlock>();
        HashSet<SsaBasicBlock> visited = new HashSet<SsaBasicBlock>();
        worklist.add(in);

        while (!worklist.isEmpty()) {
            int wsize = worklist.size();
            SsaBasicBlock v = worklist.get(wsize - 1);
            DFSInfo vbbInfo = info[v.getIndex()];
            SsaBasicBlock vAncestor = vbbInfo.ancestor;
            DFSInfo vabbInfo = info[vAncestor.getIndex()];

            // Make sure we process our ancestor before ourselves.
            if (visited.add(vAncestor) && vabbInfo.ancestor != null) {
                worklist.add(vAncestor);
                continue;
            }
            worklist.remove(wsize - 1);

            // Update based on ancestor info.
            if (vabbInfo.ancestor == null) {
                continue;
            }
            SsaBasicBlock vAncestorRep = vabbInfo.rep;
            SsaBasicBlock vRep = vbbInfo.rep;
            if (info[vAncestorRep.getIndex()].semidom
                    < info[vRep.getIndex()].semidom) {
                vbbInfo.rep = vAncestorRep;
            }
            vbbInfo.ancestor = vabbInfo.ancestor;
        }
    }
}
 
Example 15
Project: openjdk-jdk10   File: NameConverter.java   View Source Code Vote up 4 votes
/**
 * Computes a Java package name from a namespace URI,
 * as specified in the spec.
 *
 * @return
 *      null if it fails to derive a package name.
 */
public String toPackageName( String nsUri ) {
    // remove scheme and :, if present
    // spec only requires us to remove 'http' and 'urn'...
    int idx = nsUri.indexOf(':');
    String scheme = "";
    if(idx>=0) {
        scheme = nsUri.substring(0,idx);
        if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") )
            nsUri = nsUri.substring(idx+1);
    }

    // tokenize string
    ArrayList<String> tokens = tokenize( nsUri, "/: " );
    if( tokens.size() == 0 ) {
        return null;
    }

    // remove trailing file type, if necessary
    if( tokens.size() > 1 ) {
        // for uri's like "www.foo.com" and "foo.com", there is no trailing
        // file, so there's no need to look at the last '.' and substring
        // otherwise, we loose the "com" (which would be wrong)
        String lastToken = tokens.get( tokens.size()-1 );
        idx = lastToken.lastIndexOf( '.' );
        if( idx > 0 ) {
            lastToken = lastToken.substring( 0, idx );
            tokens.set( tokens.size()-1, lastToken );
        }
    }

    // tokenize domain name and reverse.  Also remove :port if it exists
    String domain = tokens.get( 0 );
    idx = domain.indexOf(':');
    if( idx >= 0) domain = domain.substring(0, idx);
    ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) );
    if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) {
        // remove leading www
        r.remove( r.size()-1 );
    }

    // replace the domain name with tokenized items
    tokens.addAll( 1, r );
    tokens.remove( 0 );

    // iterate through the tokens and apply xml->java name algorithm
    for( int i = 0; i < tokens.size(); i++ ) {

        // get the token and remove illegal chars
        String token = tokens.get( i );
        token = removeIllegalIdentifierChars( token );

        // this will check for reserved keywords
        if (SourceVersion.isKeyword(token.toLowerCase())) {
            token = '_' + token;
        }

        tokens.set( i, token.toLowerCase() );
    }

    // concat all the pieces and return it
    return combine( tokens, '.' );
}
 
Example 16
Project: ZooKeeper   File: OOMTest.java   View Source Code Vote up 4 votes
@Test
public void testOOM() throws IOException, InterruptedException, KeeperException {
    // This test takes too long tos run!
    if (true)
        return;
    File tmpDir = ClientBase.createTmpDir();
    // Grab some memory so that it is easier to cause an
    // OOM condition;
    ArrayList<byte[]> hog = new ArrayList<byte[]>();
    while (true) {
        try {
            hog.add(new byte[1024 * 1024 * 2]);
        } catch (OutOfMemoryError e) {
            hog.remove(0);
            break;
        }
    }
    ClientBase.setupTestEnv();
    ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);

    final int PORT = PortAssignment.unique();
    ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
    f.startup(zks);
    Assert.assertTrue("waiting for server up",
               ClientBase.waitForServerUp("127.0.0.1:" + PORT,
                                          CONNECTION_TIMEOUT));

    System.err.println("OOM Stage 0");
    utestPrep(PORT);
    System.out.println("Free = " + Runtime.getRuntime().freeMemory()
            + " total = " + Runtime.getRuntime().totalMemory() + " max = "
            + Runtime.getRuntime().maxMemory());
    System.err.println("OOM Stage 1");
    for (int i = 0; i < 1000; i++) {
        System.out.println(i);
        utestExists(PORT);
    }
    System.out.println("Free = " + Runtime.getRuntime().freeMemory()
            + " total = " + Runtime.getRuntime().totalMemory() + " max = "
            + Runtime.getRuntime().maxMemory());
    System.err.println("OOM Stage 2");
    for (int i = 0; i < 1000; i++) {
        System.out.println(i);
        utestGet(PORT);
    }
    System.out.println("Free = " + Runtime.getRuntime().freeMemory()
            + " total = " + Runtime.getRuntime().totalMemory() + " max = "
            + Runtime.getRuntime().maxMemory());
    System.err.println("OOM Stage 3");
    for (int i = 0; i < 1000; i++) {
        System.out.println(i);
        utestChildren(PORT);
    }
    System.out.println("Free = " + Runtime.getRuntime().freeMemory()
            + " total = " + Runtime.getRuntime().totalMemory() + " max = "
            + Runtime.getRuntime().maxMemory());
    hog.get(0)[0] = (byte) 1;

    f.shutdown();
    zks.shutdown();
    Assert.assertTrue("waiting for server down",
               ClientBase.waitForServerDown("127.0.0.1:" + PORT,
                                            CONNECTION_TIMEOUT));
}
 
Example 17
Project: RoughWorld   File: RoughWorld.java   View Source Code Vote up 4 votes
public void run()
{
	ArrayList<WebRequest> requestToProcess = new ArrayList<WebRequest>();

	while(keepRunning)
	{
		webInterface.getQueue(requestToProcess);

		for(int i = 0; i < requestToProcess.size(); i++) 
		{
	        WebRequest toProcess = requestToProcess.remove(i);

	        if(toProcess.path.length()==0)
	        	toProcess.path = "Index.html";
	        
	        boolean processed = false;
	        for(int pi = 0; pi<pages.size(); pi++)
	        {
	        	DynamicWebPage p = pages.get(pi);
	        	if(p.process(toProcess))
	        	{
	        		processed = true;
	        		toProcess.r = new WebResponse( WebResponse.HTTP_OK, WebResponse.MIME_HTML, p, null );		        	
	        		break;
	        	}
	        }
	        
	        if(!processed)
	        {
	        	toProcess.r = new WebResponse( WebResponse.HTTP_NOTFOUND, WebResponse.MIME_PLAINTEXT,
						 "Error 404, file not found." );
	        }
	        //create a new thread that will send the response to the webbrowser
			Thread t = new Thread( toProcess );
			//daemon means that even if the program is closed this thread will continue until
			//it is finished
			t.setDaemon( true );
			//this starts the thread running
			t.start();

		}
		//This command pauses the update loop for 10 milliseconds
		//the goal is to have the total time to calculate each loop be under 16.7 milliseconds
		//if this performance goal is reached then the server will be able to respond to
		//changes faster than the eye can detect changes 
		//if a graphical user interface were added to this application 
		//it would appear to be responding instantaneously
		try
		{
			Thread.sleep(10);
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
	}
}
 
Example 18
Project: Kaeon-FUSION   File: Build.java   View Source Code Vote up 4 votes
public Object onCommand(Element element, ArrayList<Object> processed) {
	
	ArrayList<String> tags = new ArrayList<String>();
	
	tags.add("Build");
	tags.add(element.getElement(0).getContent());
	
	ArrayList<Element> arguments = new ArrayList<Element>();
	
	arguments.addAll(element.getElements());
	arguments.remove(0);
	
	try {
		return ((BuildStone) get(tags).get(0)).build(element.getElement(0).getElements(), arguments);
	}
	
	catch(Exception exception) {
		
	}
	
	return null;
}
 
Example 19
Project: faitic-checker   File: Faitic.java   View Source Code Vote up 3 votes
protected static void deleteRepeatedFiles(ArrayList<FileFromURL> list){	// Deletes files with same url

		// Make a copy of list

		int pos=0;

		while(pos<list.size()){	// From 0 to size

			FileFromURL element=list.get(pos);	// To compare

			int i=pos+1;

			while(i<list.size()){	// From pos+1 to size

				// 1 is url
				if(element.getURL().equals(list.get(i).getURL())){

					list.remove(i);	// Delete element
					i--;			// The i index must be reduced

					//out.set(i, new String[]{"Repeated:" + out.get(i)[0],out.get(i)[1]});

				}

				i++;
			}

			pos++;

		}

	}
 
Example 20
Project: Kaeon-FUSION   File: Processor.java   View Source Code Vote up 2 votes
public static Element process(
		ArrayList<String> tokens,
		ArrayList<String> tokenize,
		String nestToken) {
	
	ArrayList<Element> directives = new ArrayList<Element>();
	
	Element element = new Element();
	
	Element currentElement = element;
	
	int previousNest = 0;
	Element previousElement = element;
	
	ArrayList<Element> baseElements = new ArrayList<Element>();
	
	boolean inLiteralBlock = false;
	int literalNest = 0;
	String literalString = "";
	
	for(int i = 0; i < tokenize.size();) {
		
		ArrayList<String> line = getLine(tokenize, i);
		int nest = nest(line, nestToken);
		
		if(!inLiteralBlock) {
			
			if(nest > previousNest) {
				
				baseElements.add(currentElement);
				
				currentElement = previousElement;
			}
			
			else if(nest < previousNest) {
				
				for(int j = nest; j < previousNest && baseElements.size() > 0; j++)
					currentElement = baseElements.remove(baseElements.size() - 1);
			}
			
			previousNest = nest;
		}
		
		boolean literal =
				isLiteralBlock(line, nest) &&
				!(inLiteralBlock && nest != literalNest);
		
		if(literal) {
			inLiteralBlock = !inLiteralBlock;
			literalNest = nest;
		}
		
		if(inLiteralBlock) {
			
			if(!literal) {
				
				for(int j = literalNest + 1; j < line.size(); j++)
					literalString += line.get(j);
				
				literalString += '\n';
			}
		}
		
		else if(literal) {
			
			previousElement = cropElement(getElement(literalString), true);
			ElementUtilities.addChild(currentElement, previousElement);
			
			literalString = "";
		}
		
		else if(line.size() > 0)
			previousElement = processLine(tokens, line, currentElement, directives);
		
		i += line.size() + 1;
	}
	
	DirectiveProcessor.processDirectives(element, directives);
	
	return element;
}