0

I couldn't remove object.How can I remove a object from an arraylist?

my code

 List<kisi> x=new ArrayList<kisi>();
 x.add(new kisi("1","betül"));
 x.add(new kisi("2","hatice"));
 x.add(new kisi("3","selma"));
 kisi k=new kisi("2","hatice");
     
 for (int i = 0; i < x.size(); i++) {
 if (x.get(i).id==k.id) {
 Object obj = x.remove(i);
 break;
 }
 }

my constructor

public class kisi {
 public static String id="0";
 public static String ad="0"; 
public kisi(String id,String ad) { 
// TODO Auto-generated constructor stub 
this.id=id;
 this.ad=ad;
 }
Community
  • 1
  • 1
user3452425
  • 73
  • 2
  • 10

3 Answers3

0

Solution

Remove the statics from your member variables in your kisi class.

But also note

new kisi("1","betül")

So your id is a String.

When you go through the list comparing ids you do so with ==.

== in java is a same comparison, not an equal comparison. This is unlike the behavior for strings in C# say.

So what you should do is this:

for (int i = 0; i < x.size(); i++) {
  if (x.get(i).id.equals(k.id)) { //change here
    Object obj = x.remove(i);
    break;
  }
}

In this simple example this is not causing the problem because the two "2" strings are the same. Which leads me to conclude there's something funny going on your kisi constructor. This is the one I used and the code worked as was:

public class kisi {    
  public String id;    
  public kisi(String id, String string2) {
    this.id = id;
  }    
}

A constructor like this will break the code without the .equals call:

public kisi(String id, String string2) {
  this.id = id + string2;
}  
weston
  • 54,145
  • 21
  • 145
  • 203
  • I wan to write list element.it show only second element every iterator.for (kisi kisi : x) { Toast.makeText(getApplicationContext(),"eleman"+kisi.ad, Toast.LENGTH_LONG).show(); } – user3452425 Jun 01 '14 at 08:07
  • Post your constructor for `kisi` class. – weston Jun 01 '14 at 08:07
0

To remove an Element safely from a list while traversing it you need to do it with an iterator. Otherwise you might get strange results!

Calling remove in foreach loop in Java

Community
  • 1
  • 1
Marekzan
  • 93
  • 1
  • 9
-1

In java the only method for removing an item from a list while traversing it is via Iterator.

Dudi
  • 2,340
  • 1
  • 24
  • 39
  • What's this then: http://docs.oracle.com/javase/7/docs/api/java/util/List.html#remove(int) or why doesn't that work in his case? – weston Jun 01 '14 at 07:52
  • @weston please review http://stackoverflow.com/questions/5113016/getting-a-concurrentmodificationexception-thrown-when-removing-an-element-from-a – Dudi Jun 02 '14 at 08:52
  • You appear to be saying that you **must** use an `iterator` and `iterator.remove` if you want to remove while going though a list. That's not true. – weston Jun 02 '14 at 09:07
  • It's not a bad suggestion, but it's not the *only* method. – weston Jun 02 '14 at 09:08