• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to use Equals method .  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following program:
public static void main (String[] args)
{
ArrayList name = new ArrayList();

name.add ("Jim");
name.add ("David");
name.add ("Eddy");
name.add ("Murphy");
name.add ("David");
name.add("Don");

System.out.println (name);

I have to find all of the Array list indices where 'David' occurs and print these. I will need to loop through the ArrayList getting each entry and checking to see if it is 'David'. I have to use the method .equals to compare Strings, not == (this can only be used for primitive data types), need help to convert the below program to use equals method..

for (int i=0; i<band.size(); i++)
{
String str = "David";
if (band.get(i) ==(str))
{
System.out.println("The Strings are equal");
}
else
{
System.out.println("The Strings are not equal");
}
}
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

[ June 11, 2007: Message edited by: Joanne Neal ]
 
Bartender
Posts: 2856
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
well the above post is the required answer but, Sunali Anu missed something

I have to use the method .equals to compare Strings, not == (this can only be used for primitive data types), need help to convert the below program to use equals method..


here you are wrong,the == operator can be used for objects, there's no doubt in it.
The only thing is that wont help you in comparing object contents for equality.

Hope this helps
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Amit Ghorpade:
...the == operator can be used for objects, there's no doubt in it.
The only thing is that wont help you in comparing object contents for equality...

Just to expand on this: The == operator compares values. When applied to objects, this means it compares references. So if x and y refer to objects, then x == y will be true only if x and y point to the same instance.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!