问题描述
好吧我有一个LinkedList,我有一个String。我想检查String是否包含在任何LinkedList元素中。
例如:
Okay so I have a LinkedList, and I have a String. I want to check if the String is contained within any of the LinkedList elements.For example:
String a = "apple";
String listelement = "a bunch of apples";
LinkedList list = new LinkedList();
list.add(listelement);
if(list.containsany(a){
System.out.println("Hooray!");
}
会导致打印Hooray!
Would result in printing "Hooray!"
显然list.containsany不是真正的LinkedList方法,我'我只是为此目的使用它。
Obviously list.containsany isn't a real LinkedList method, I'm just using it for this purpose.
那么如何模拟我的例子呢?
So how can I simulate my example?
谢谢
推荐答案
String a = "apple";
String listelement = "a bunch of apples";
List<String> list = new LinkedList<String>();
list.add(listelement);
for(String s : list){
if(s.contains(a)){
syso("yes");
}
}
这应该这样做,为了找到一个包含特定字符串的节点,你需要遍历所有节点。如果你只想要一个实例,你可以打破循环。
This should do it, in order to find a node contains a particular string, you need to iterate through all the nodes. You can break the loop, if you want only 1 instance.
您还想使用Generics。查看代码。否则您必须将节点强制转换为String。
Also you want to use Generics. Look at the code. otherwise you will have to cast the node to a String.
这篇关于Java:如何检查字符串是否是任何LinkedList元素的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!