java 比较存储在 ArrayList 中的字符串元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5210433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing string elements stored in ArrayList
提问by athresh
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.
我能怎么做?请帮忙。
回答by michal.kreuzman
use list.contains(Object o)
to check if list contains String
. For comparing of String
use "a".equals(list.get(0))
method.
用于list.contains(Object o)
检查列表是否包含String
. 用于比较String
使用"a".equals(list.get(0))
方法。
回答by Jeremy
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)
回答by The Scrum Meister
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
}
回答by lukastymo
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
所以这是对 Array 和 String 的基本操作。您可以在 Michal 的帖子中回答您的问题。但是你可以阅读一些关于它的指南并自己做
Oracle have nice tutorial about Arraysand for String you can find "String comparison" or just find method to compare in documentation String class in Java 1.6
Oracle 有关于数组的很好的教程,对于字符串,您可以找到“字符串比较”或只是在 Java 1.6 的文档字符串类中找到要比较的方法