Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 415
  • Last Modified:

arraylist objects

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
fattoo
Asked:
fattoo
  • 8
  • 7
1 Solution
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
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
 
fattooAuthor Commented:
is there any other way even if the code is completely different from mine

many thanks
0
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
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
 
fattooAuthor Commented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
fattooAuthor Commented:
i really cannot thank you more

it is finally working

i really appreciate your kind help

thank you soooo much :)
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 8
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now