1

How would I be able to access specific strings with and array list?

List<String> myList = new ArrayList<String>();
myList.Add("Hi");
myList.Add("Pizza");
myList.Add("Can");

So if I did that and then I do:

for (String s : myList)
    if (s == "Hi")
        system.out.println("Hello"):

It would not print "Hello".

I need the size to change and see if the string exists but I can't seem to get this to work, any ideas?

2
  • 1
    You can't use == to test non-primitive objects for equality, generally. Override Object.equals() meaningfully and use it. Commented Dec 2, 2012 at 14:04
  • 1
    seems you are just using the loop for checking whether "Hi" is present or not. So for that list.contains("Hi") can also be used. Commented Dec 2, 2012 at 14:07

8 Answers 8

1

- Objects in Java are compared using equals(), and String is an Object in Java, so it follows the same rule.

- == will be used to compare primitive or to check if two or more Object Reference Variables are pointing to the same Object on the heap or not.

- So you should use equals() or equalsIgnoreCase() (if case doesn't matters) to compare the String Objects.

for (String s : myList){
    if (s.equals("Hi"))
        system.out.println("Hello");
}
Sign up to request clarification or add additional context in comments.

Comments

1
 if (s == "Hi")

change it to

 if (s.equals("Hi"))

It is always better to use equals() while comparing objects than using == (except String literals)

== compares reference equality. equals() compares object content equality.

Comments

1

You should write below code

for (String s : myList)
    if (s.equals("Hi"))
        system.out.println("Hello"):

Comments

1

You could use s.equalsIgnoreCase("Hi") if you do not care about upper-/lowercase

1 Comment

but s.equals("Hi") is more than enough.
1

You should use .equals() method it will check the value of the string while == checke Object reference.

Comments

1

Method name is add(object) not `Add(). Here is an another answer

        List<String> myList = new ArrayList<String>();
        myList.add("Hi");
        myList.add("Pizza");
        myList.add("Can");
        // method 1
        if( myList.contains("Hi")) {
            System.out.println("Found");
        }
        // method 2
        for( String word : myList ) {
            if( word.equals("Hi")) {
                System.out.println("found");
                // break the loop to avoid continues iteration
                break;
            }
        }

Comments

0

Why not use List.contains()?

if (myList.contains("Hi"))
    system.out.println("Hello");

Comments

0

Why you don't use a HashMap? You can access the value by the get method of the HashMap. You will avoid to make a loop on the ArrayList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.