Javatpoint Logo

please explain the following program?

By: sarath*** On: Fri Sep 06 04:49:33 EDT 2013     Question Reputation3 Answer Reputation0 Quiz Belt Series Points0  3Blank User
import java.util.*;

public class Test{

public static void main(String ar[]){

ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");

for(int i=1;i<=list.size();i++){

if(list.equals("3")){

list.remove("3");
}+

System.out.println(i);
}
}
}


when i execute the above program it prints outputs 1,2,3,4,5 instead of 1,2,4,5...

Up0Down

 
Hi Sarath,

First u should know two things. 1. Content Comparison. 2. Reference Comparision

So here in if(list.equals("3")) u r using equals method.

In the list object, it holds multiple objects which are defined as string, as placed the content in " double quotes".

So it treats as object.

When u r saying, list.equals("3") , u r comparing("3") a string object,
with the list object which hold multiple string object.

so when it encountere "3" in the list object. The control will come to remove method. so it is removing 3,(which is treated as string object) from the list.

Here It is reflexive: for any non-null reference value x, x.equals(x) should return true.

As the encountered values is matching "3", it removed from the list object.

So that's y output 1,2,4,5.

So it is doing content comparision.

Reason y i said to go thru with diff of 1.Content Comparision 2. Reference Comparision, u will get clear idea, when u r using Hashmap n WeakHashmap etc.

equals method is defined in java.lang package.

If any help required kindly let me know.

Thanks & Regards
JhonShravan
Image Created0Down

By: [email protected] On: Fri Sep 06 07:08:51 EDT 2013 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :2Yes3No
 
@jhonshravan : the above program prints 1,2,3,4,5. you are explaining why it prints 1,2,4,5. ????

if(list.equals("3")){

list.remove("3"); // this line never executes
}+
Image Created0Down

By: [email protected] On: Tue Sep 10 22:58:16 EDT 2013 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :3Yes1No
 
No need to iterate for your desired result...just write the following.
List list=new ArrayList();

if(list.contains("3")){

list.remove("3");
}
Image Created0Down

By: [email protected] On: Tue Sep 17 03:13:36 EDT 2013 Question Reputation5 Answer Reputation20 Belt Series Points0 25User Image
Are You Satisfied :1Yes0No