athresh
athresh

Reputation: 161

Comparing string elements stored in ArrayList

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.

Upvotes: 2

Views: 12585

Answers (4)

michal.kreuzman
michal.kreuzman

Reputation: 12390

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

Upvotes: 6

lukastymo
lukastymo

Reputation: 26799

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

Upvotes: 0

Jeremy
Jeremy

Reputation: 22415

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)

Upvotes: 4

The Scrum Meister
The Scrum Meister

Reputation: 30111

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
}

Upvotes: 0

Related Questions