Raised This Month: $32 Target: $400
 8% 

Solved Looping Arraylists


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
Chrissy
Member
Join Date: May 2013
Old 10-29-2019 , 17:27   Looping Arraylists
Reply With Quote #1

How would you guys go about looping through an arraylist, and erasing indexes based on an if statement. I'm drawing a blank on how to do it. Everytime you erase the length is smaller and the stack is dropped down an index.

For example:
Code:
ArrayList Gartfeild = new ArrayList();

Gartfeild.Push(1);
Gartfeild.Push(2);
Gartfeild.Push(1);
Gartfeild.Push(3);
Gartfeild.Push(1);

//ArrayList 0 - 4  = {1,2,1,3,1}

for(int i; i < Gartfeild.Length; i++)
{
	if(Gartfeild.Get(i) == 1)
	{
		Gartfeild.Erase(i);
	}
}

Last edited by Chrissy; 11-01-2019 at 15:11.
Chrissy is offline
8guawong
AlliedModders Donor
Join Date: Dec 2013
Location: BlackMarke7
Old 10-29-2019 , 21:59   Re: Looping Arraylists
Reply With Quote #2

Start the loop from the back
__________________
8guawong is offline
MAGNAT2645
Senior Member
Join Date: Nov 2015
Location: AlliedMods.net
Old 10-29-2019 , 22:48   Re: Looping Arraylists
Reply With Quote #3

Also you shouldn't use functions inside loop's condition check.
You can replace it with:
Code:
int iLength = Gartfeild.Length;
for (int i = 0; i < iLength; i++)
or even with
Code:
for (int i = 0, iLength = Gartfeild.Length; i < iLength; i++)
And in your case, as 8guawong said, you can do backward iteration:
Code:
for (int i = Gartfeild.Length - 1; i >= 0; i--)
__________________

Last edited by MAGNAT2645; 10-29-2019 at 22:50.
MAGNAT2645 is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 20:52.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode