Java ArrayList<String> 中 contains 的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3943582/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:20:14  来源:igfitidea点击:

Use of contains in Java ArrayList<String>

javaarraylist

提问by Mr Morgan

If I have an ArrayList of String forming part of a class in Java like so:

如果我有一个 String 的 ArrayList 构成 Java 类的一部分,如下所示:

private ArrayList<String> rssFeedURLs;

private ArrayList<String> rssFeedURLs;

If I want to use a method in the class containing the above ArrayList, using ArrayList contains to check if a String is contained in this ArrayList, I believe I should be able to do so as follows:

如果我想在包含上述ArrayList的类中使用一个方法,使用ArrayList contains来检查这个ArrayList中是否包含一个String,我相信我应该能够这样做:

if (this.rssFeedURLs.contains(rssFeedURL)) {

Where rssFeedURL is a String.

其中 rssFeedURL 是一个字符串。

Am I right or wrong?

我是对还是错?

回答by Aaron McIver

Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.

是的...使用字符串...当您偏离原语或字符串时,事情就会发生变化,您需要实现哈希码/等于以获得所需的效果。

EDIT: Initialize your ArrayList<String>then attempt to add an item.

编辑:初始化您ArrayList<String>然后尝试添加一个项目。

回答by willcodejavaforfood

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSetis OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

是的,这应该适用于字符串,但如果您担心重复,请使用Set. 此集合可防止重复,而您无需执行任何操作。AHashSet可以使用,但它是无序的,因此如果您想保留插入顺序,请使用LinkedHashSet.

回答by wds

Perhaps you need to post the code that caused your exception. If the above is all you have, perhaps you just failed to actually initialise the array.

也许您需要发布导致异常的代码。如果以上就是你所拥有的,也许你只是没有真正初始化数组。

Using contains here should work though.

不过,在这里使用 contains 应该可以。

回答by Andy Thomas

You are right. ArrayList.contains() tests equals(), not object identity:

你是对的。ArrayList.contains() 测试 equals(),而不是对象标识:

returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

当且仅当此列表包含至少一个元素 e 使得 (o==null ? e==null : o.equals(e)) 时才返回 true

If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:

如果您遇到 NullPointerException,请验证您是否在构造函数或声明中初始化了您的列表。例如:

private List<String> rssFeedURLs = new ArrayList<String>();

回答by haylem

Your question is not very clear.

你的问题不是很清楚。

  • What's your code exactly doing? Give more code.
  • What's the error you're getting?
  • 你的代码到底在做什么?给更多的代码。
  • 你得到的错误是什么?

You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().

你说你得到一个空指针。您无法获得空指针作为 返回的值contains()

However you can get a NullPointerExceptionif your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.

但是,NullPointerException如果您的列表尚未初始化,您可以获得一个。现在通过阅读您的问题,我会说您在此处显示的内容是正确的,但也许您只是没有实例化列表。

For this to work (to add a feed URL if it isn't already in the list):

要使其工作(如果它不在列表中,则添加提要 URL):

if (!this.rssFeedURLs.contains(rssFeedURL)) {
    this.rssFeedURLs.add(rssFeedUrl);
}

then this declaration would do:

那么这个声明会做:

private ArrayList<String> rssFeedURLs = new ArrayList<String>();

or initialize your list later on, but before trying to access its methods:

或稍后初始化您的列表,但在尝试访问其方法之前:

rssFeedUrls = new ArrayList<String>();


Finally... Do you really need a List? Maybe a Setwould be better if you don't want duplicates. Use a LinkedHashSetif preserving the ordering matters.

最后...你真的需要一个List吗?Set如果您不想重复,也许 a会更好。LinkedHashSet如果保留排序问题,请使用 a 。

回答by Aviad Ben Dov

You're correct. As others said according to your comments, you probably did not initialize your ArrayList.

你是对的。正如其他人根据您的评论所说,您可能没有初始化您的 ArrayList。

My point is different: you claimed that you're checking for duplicates and this is why you call the contains method. Try using HashSet. It should be more efficient - unless you need to keep the order of URLs for any reason.

我的观点不同:您声称您正在检查重复项,这就是您调用 contains 方法的原因。尝试使用HashSet. 它应该更有效 - 除非您出于任何原因需要保持 URL 的顺序。

回答by Michael McGowan

You are right that it should work; perhaps you forgot to instantiate something. Does your code look something like this?

你是对的,它应该起作用;也许你忘了实例化一些东西。你的代码看起来像这样吗?

String rssFeedURL = "http://stackoverflow.com";
this.rssFeedURLS = new ArrayList<String>();
this.rssFeedURLS.add(rssFeedURL);
if(this.rssFeedURLs.contains(rssFeedURL)) {
// this code will execute
}

For reference, note that the following conditional will also execute if you append this code to the above:

作为参考,请注意,如果将此代码附加到上面,以下条件也将执行:

String copyURL = new String(rssFeedURL);
if(this.rssFeedURLs.contains(copyURL)) {
// code will still execute because contains() checks equals()
}

Even though (rssFeedURL == copyURL) is false, rssFeedURL.equals(copyURL) is true. The contains method cares about the equals method.

尽管 (rssFeedURL == copyURL) 为假,但 rssFeedURL.equals(copyURL) 为真。contains 方法关心 equals 方法。

回答by Mr Morgan

Thanks to you all for answering so quickly. I could always use a set but I have the ArrayList working now. The problem was that in the constructor of the class containing the ArrayList, I was not saying:

谢谢大家这么快回复。我总是可以使用一个集合,但我现在可以使用 ArrayList。问题是在包含 ArrayList 的类的构造函数中,我没有说:

public RSS_Feed_Miner() {
    ...
    this.rssFeedURLs = new ArrayList<String>();
    ... 
}

D'Oh! for a Friday afternoon.

哦!周五下午。

回答by Thilina Anuradh

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

.....

newlyAddedTypes.add("test1");

newlyAddedTypes.add("test1");

newlyAddedTypes.add("test2");

if(newlyAddedTypes.contain("test"){
//called here
}
else{

}

回答by Syed Danish Haider

In the below code we have taskfilled as arraylist,retrieveTaskidForDelete as method by which we add the value in task filled arraylist and checkid is String.we need to check if the string value contain in arraylist.

在下面的代码中,我们将任务填充为数组列表,retrieveTaskidForDelete 作为方法,我们通过该方法将任务填充的数组列表中的值添加到检查ID 为字符串中。我们需要检查字符串值是否包含在数组列表中。

String checkid;
ArrayList<String> taskfilled=retrieveTaskidForDelete();
                if(!taskfilled.contains(checkid)) {
                    Toast.makeText(getContext(),"Yepiee 
 Bingo"+ti.get(a),Toast.LENGTH_SHORT).show();
                }