问题
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!");
}
Would result in printing "Hooray!"
Obviously list.containsany isn't a real LinkedList method, I'm just using it for this purpose.
So how can I simulate my example?
Thanks
回答1:
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.
Also you want to use Generics. Look at the code. otherwise you will have to cast the node to a String.
回答2:
String a = "apple";
String listelement = "a bunch of apples";
LinkedList<String> list = new LinkedList<String>();
list.add(listelement);
Iterator<String> li = list.iterator();
while (li.hasNext()) {
if (li.next().contains(a)) {
System.out.println("Hooray!");
}
}
回答3:
linkedlist has a contains method in it.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html#contains(java.lang.Object)
回答4:
You would have to iterate across the list, and check each node's value to see if it was a string. If you can guarantee that all members of the linked list should be strings, using Java's Generics to force them all to be Strings may help.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;
import java.util.LinkedList;
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String a = "apple";
String listelement = "a bunch of apples";
LinkedList<String> list = new LinkedList<String>();
list.add(listelement);
list.add(new String("boogie"));
for (String s : list) {
if (s.contains(a)) {
System.out.println("yes," + s + " contains " + a);
} else {
System.out.println("no," + s + " does not contain " + a);
}
}
}
}
来源:https://stackoverflow.com/questions/7829034/java-how-to-check-if-a-string-is-a-part-of-any-linkedlist-element