Solved

arraylist objects

Posted on 2013-11-11
16
379 Views
Last Modified: 2013-11-11
hi

i have an array list of objects in java  like this:
ArrayList = {("a",2),("a",3),("b",10),("a",0),("b",8)};
i would like to loop through all the objects in this array and if the first attribute in the object is the same as the other it computes the second attribute with the rest like this
first check the first object contains "a" it will check if the rest of the elements contain "a" and if does it compute the second attribute like this

2+3+0 = 5
then create another arraylist contain the object ("a",5)
then see "b" 10+8 = 18
and then the second object in the new arraylist will be ("b",18)

this is my code so far
it i not working

for (int i = 0 ; i < poll.size()-1 ; i++)
			{
				int total = 0;
				for (int j = i+1 ; j < poll.size() ; j++)
				{				
					if (poll.get(i).getPlayer().equals(poll.get(j).getPlayer()))
					{

						total += poll.get(i).getFitness()+poll.get(j).getFitness();

						poll.remove(poll.get(j));							
					}

				}

				Fitness_List newFitness = new Fitness_List(poll.get(i).getPlayer(),total);

				newArray.add(newFitness);

			}

Open in new window

0
Comment
Question by:fattoo
  • 8
  • 7
16 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 39640217
If it was me I would probably do this is a slightly different way, but to get your code to work you would need to do a couple of things...

Where you accumulate the total on line 9, the logic is wrong. The way that you have it, will include the first value in the total each time around the loop, eg. in your example for "a" the total should be 2 + 3 + 0 = 5, but your code would look something like this...   0   +    ( 2 + 3 )    +    ( 2 + 0 )    =    7.     The first 0 in that is the initial value of total that you set on line 3, the (2 + 3) is from the first iteration where the "a"s match and the ( 2 + 0 ) is from the second iteration where the "a"s match. Your code is almost right, you just need to change it to this...

line 3   --->    int total = poll.get(i).getFitness();

and

line 9   --->    total += poll.get(j).getFitness();


The next issue is on line 11. The problem is that when you remove an element, all the others after it move to the left by one to fill the gap, but since your inner for loop is still going to increment the j counter variable, you will "miss" an element everytime you remove one. (Also, you can remove elements just by index so you can simplify that remove line). It should look something like this... (replace line 11 with the following 2 lines)

poll.remove(j);           // Removes the element at index   j
j--;                               // Decrements j to account for the fact that all subsequent elements have shifted


Lastly, on line 1 to set the loop limit to be "poll.size() - 1". This means that you would actually miss an element if the last element in the list is a different "player" name. For example, if you were to add a ("c", 7) element to the example you gave above, it would not appear in the "newArray" at the end.   So you should change the loop limit of that outer loop (on line 1) to just be "poll.size()".
0
 

Author Comment

by:fattoo
ID: 39640254
thanks for your help but nothing happens
when i run the program first time there is no output of the new array in the output screen
and when i run it again this what appears in the output screen

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space


any help please

i think the ploblem with j--;
0
 

Author Comment

by:fattoo
ID: 39640255
is there any other way even if the code is completely different from mine

many thanks
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39640261
when i run the program first time there is no output of the new array in the output screen
There is nothing in the above code the outputs anything. Can you post your full code? That will also let me see your changes that you made to verify that they are correct.
0
 

Author Comment

by:fattoo
ID: 39640274
this is  a part of my project

			ArrayList<Fitness_List> newArray = new ArrayList<Fitness_List>();


			//assign the objects in players_list array list to poll new array list
			ArrayList<Fitness_List> poll  = new ArrayList<Fitness_List>();

			poll.clear();
			poll = players_list;
			
			
			int total = 0;
			
		
			for ( int i = 0 ; i < poll.size() ; i++)
			
			{
				
				total = poll.get(i).getFitness();

				for (int j = i+1 ; j < poll.size() ; j++)
				{				
					 
					
					if (poll.get(i).getPlayer().equals(poll.get(j).getPlayer()))
					{

						
						total += poll.get(j).getFitness();

						j--;

					}

					Fitness_List newFitness = new Fitness_List(poll.get(i).getPlayer(),total);

					newArray.add(newFitness);
				}

				
			}
			
			
			System.out.println(newArray);
			System.out.println(newArray.size());
			
			newArray.clear();

Open in new window


the reason why i initialize total to zero is that because i used the print method outside for loop
0
 

Author Comment

by:fattoo
ID: 39640291
sorry this is the code

ArrayList<Fitness_List> newArray = new ArrayList<Fitness_List>();


			//assign the objects in players_list array list to poll new array list
			ArrayList<Fitness_List> poll  = new ArrayList<Fitness_List>();

			poll.clear();
			poll = players_list;
			
			
			int total = 0;
			
		
			for ( int i = 0 ; i < poll.size() ; i++)
			
			{
				
				total = poll.get(i).getFitness();

				for (int j = i+1 ; j < poll.size() ; j++)
				{				
					 
					
					if (poll.get(i).getPlayer().equals(poll.get(j).getPlayer()))
					{

						
						total += poll.get(j).getFitness();

						//poll.remove(poll.get(j));
						j--;

					}

					
				}

				Fitness_List newFitness = new Fitness_List(poll.get(i).getPlayer(),total);

				newArray.add(newFitness);
			}
			
			
			System.out.println(newArray);
			System.out.println(newArray.size());
			
			
			newArray.clear();

Open in new window

0
 
LVL 35

Expert Comment

by:mccarl
ID: 39640306
Ok, so the OutOfMemoryError is because your inner loop gets itself into an infinite loop looking at the next "a" player in the ArrayList. You inserted the "j--;" line correctly but then you have taken the ".remove()" line out for some reason, so j doesn't get updated at all and you have your infinite loop.

Go back and read my second dot point carefully. The "remove" call stays (I was just giving you a more efficient alternative) and then the the j-- fixes the problem.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:fattoo
ID: 39640315
when you see my code there is // before  poll.remove(poll.get(j)); which means java regarded as a comment

and when i compile my program it take a while then this what appear in the output screen

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space



any help please :(

do you think the problem with the inner loop

 for (int j = i+1 ; j < poll.size() ; j++)
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39640337
when you see my code there is // before  poll.remove(poll.get(j)); which means java regarded as a comment
That is EXACTLY the problem... it should NOT be a comment. It should be a normal statement so that it gets executed!
0
 

Author Comment

by:fattoo
ID: 39640375
i removed it as you said

but when i run the program, the program is not terminated and there was nothing in the output screen, i have been waiting for 3 min and i had to close the output screen myself

you mentioned before if you were me you would change the code to different code

can you let me please about the code that you would create it and i will try it

many thanks for helping me
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39640390
i removed it as you said
Did you remove just the // at the front of the line or the whole line?  Can you post the code again as it currently stands so I can check?
0
 

Author Comment

by:fattoo
ID: 39640405
this is the code again

ArrayList<Fitness_List> newArray = new ArrayList<Fitness_List>();


			//assign the objects in players_list array list to poll new array list
			ArrayList<Fitness_List> poll  = new ArrayList<Fitness_List>();

			poll.clear();
			poll = players_list;
			
			
			int total = 0;
			
		
			for ( int i = 0 ; i < poll.size() ; i++)
			
			{
				
				total = poll.get(i).getFitness();

				for (int j = i+1 ; j < poll.size() ; j++)
				{				
					 
					
					if (poll.get(i).getPlayer().equals(poll.get(j).getPlayer()))
					{

						
						total += poll.get(j).getFitness();

						j--;

					}
				}

				Fitness_List newFitness = new Fitness_List(poll.get(i).getPlayer(),total);

				newArray.add(newFitness);
			}
			
			
			System.out.println(newArray);
			System.out.println(newArray.size());
			
			
			newArray.clear();

Open in new window

i think that i need to add a condition to if statement
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39640444
AGAIN I say, where is the line to remove the object from the poll arraylist?  I didn't say to remove that whole line, just to make it NOT a comment.

Since you don't seem to be understanding my instructions... here is the code that I have been trying to get you to, even though I have pretty much already done that. Maybe I have confused you with trying to optimize the .remove() method call as well as fix the problem, so I will start just by using the version that you originally had... so replace the section that you just posted with this...
ArrayList<Fitness_List> newArray = new ArrayList<Fitness_List>();


			//assign the objects in players_list array list to poll new array list
			ArrayList<Fitness_List> poll  = new ArrayList<Fitness_List>();

			poll.clear();
			poll = players_list;
			
			
			int total = 0;
			
		
			for ( int i = 0 ; i < poll.size() ; i++)
			
			{
				
				total = poll.get(i).getFitness();

				for (int j = i+1 ; j < poll.size() ; j++)
				{				
					 
					
					if (poll.get(i).getPlayer().equals(poll.get(j).getPlayer()))
					{

						
						total += poll.get(j).getFitness();

						poll.remove(poll.get(j));
						j--;

					}
				}

				Fitness_List newFitness = new Fitness_List(poll.get(i).getPlayer(),total);

				newArray.add(newFitness);
			}
			
			
			System.out.println(newArray);
			System.out.println(newArray.size());
			
			
			newArray.clear();

Open in new window

See line 30 of what I have just posted, it is PRESENT and it is NOT commented out
0
 

Author Comment

by:fattoo
ID: 39640468
i really cannot thank you more

it is finally working

i really appreciate your kind help

thank you soooo much :)
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39640493
So what I was trying to say, way back in that earlier post was that you can now change line 30 of my last post to this...
			poll.remove(j);

Open in new window

It will be much more efficient, as it can just directly remove the element at the index in j       Your original version of that line, gets the element at index j and then asks the list to remove that element. However to remove in this fashion, the list will actually step through each element to find "where" that element is in the list and then remove it.


And thanks for accepting, and your nice comments! :)

Oh, and then reason that I was hesitant in just providing the code for the way that I would have done it, is that I think that it is more beneficial for your learning to get your own ideas working, rather than just use ideas from someone else. Good luck with your programming!
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Okay. So what exactly is the problem here? How often have we come across situations where we need to know if two strings are 'similar' but not necessarily the same? I have, plenty of times. Until recently, I thought any functionality like that wo…
Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now