2

I have a string arraylist

ArrayList<String> data = new ArrayList<String>();

and I have stored string values inside. Now i want to do something like

data.get(0) == "a" // (need to compare)

How can I do? please help out.

4 Answers 4

6

use list.contains(Object o) to check if list contains String. For comparing of String use "a".equals(list.get(0)) method.

Sign up to request clarification or add additional context in comments.

2 Comments

Small point, I recommend "a".equals(list.get(0)) instead of list.get(0).equals("a")
@smas You're right, it prevets potencial NullPointerException if null is in array list. I've edited it.
4

Here is some code to play with:

ArrayList<String> data = new ArrayList<String>();
data.add("a")
data.add("b")
data.add("c")

To check for equality:

data.get(0).equals("a"); // true
data.get(0).equals("b"); // false

To check for order:

data.get(0).compareTo("a"); // 0 (equal)
data.get(0).compareTo("b"); // -1 (a is less than b)

Comments

0
if(data.size() > 1 && "a".equals((String)data.get(0))) {
  //do something
}

You should really use generics:

ArrayList<String> data = new ArrayList<String>();
if(data.size() > 1 && "a".equals(data.get(0))) {
  //do something
}

Comments

0

So this is basic operations on Array and String. You have answer for your questions in Michal's post. But you can read some guide about it and do it by yourself

Oracle have nice tutorial about Arrays and for String you can find "String comparison" or just find method to compare in documentation String class in Java 1.6

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.