user1870398
user1870398

Reputation:

Using An ArrayList To Access Specific Objects Java

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?

Upvotes: 1

Views: 140

Answers (8)

user1869209
user1869209

Reputation:

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

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32014

Why not use List.contains()?

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

Upvotes: 0

vels4j
vels4j

Reputation: 11298

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;
            }
        }

Upvotes: 1

Kanagaraj M
Kanagaraj M

Reputation: 966

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

Upvotes: 1

Nabil A.
Nabil A.

Reputation: 3400

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

Upvotes: 1

Bhavik Ambani
Bhavik Ambani

Reputation: 6667

You should write below code

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

Upvotes: 1

kosa
kosa

Reputation: 66677

 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.

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

- 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");
}

Upvotes: 1

Related Questions