Wednesday 15 July 2015

java - Unique Integers From Array List -


I'm having trouble creating a method that will return a specific integer to the array list. I really want to do this with the removal of the duplicates and then just display the array list. I do not know what the problem is when I check it, I get this output: [3, 11, 33, 10]

This is my code

  Package getUniques; Import java.util.ArrayList; Public Sector Unix {Public Fixed Arrestist & lt; Integer & gt; GetUniques (ArrayList & lt; integer & gt; list) {int i = 0; While (i & lt; list.size () - 1) {for (int j = 0; j & lt; list.size (); j ++) {if (list.get (i) == list.get (J)) list.remove (i); } I ++; } Return list; } Public static zero main (string [] args) {ArrayList & lt; Integer & gt; List = New Arrestist & lt; Integer & gt; (); List.add (3); List.add (3); List.add (5); List.add (11); List.add (22); List.add (33); List.add (22); List.add (10); Println (getUniques (list)); }}   

There are some problems with your code These are the fixes for your existing code:

Before you remove the wrong index, you have identified the element as a duplicate on j ; Rather than remove it instead of element at i .

  list.remove (j); // j not i   

Next, you are removing all elements, and you are not leaving "original". To fix this, simply check (and remove) the <(0)> previous i loop in the loop.

 for  (int j = i + 1; j & lt; list size (); j ++) {// start from i + 1, not 0.  < / Pre> 

After that you will need to redo your j index, it has been deleted, because the remaining elements have been moved back to the 1st place. Instead

  if (list.get (i) == list.get (j)) list.remove (i);   

Try

  if (list.get (i) == list.get (j)) {list.remove (j); J--; // J Try again next loop, once it has increased again}    

No comments:

Post a Comment