However, the two collections share the contains() to check if the list (in our case TreeSet) contains a specific element. You can browse TreeSet with Iterator and test equality with the condition if(o1.equals(o2)) until it reaches the desired element. Here we are talking about Set, so the elements are mixed and don't have a precise index.
import java.util.Iterator;Compiling and executing this code results in this:
import java.util.TreeSet;
public class search_element {
public static void main(String[] args) {
// creating TreeSet
TreeSettset = new TreeSet ();
// populate TreeSet
tset.add("abc");
tset.add("bcd");
tset.add("cde");
tset.add("def");
tset.add("efg");
String e = "def";
// check for the existence of a specific element in TreeSet
boolean exists = tset.contains(e);
System.out.println(e+" exists in treeset? "+exists);
String e2 = "eee";
exists = tset.contains(e2);
System.out.println(e2+" exists in treeset? "+exists);
Iteratoriterator = tset.iterator();
// search for the element and test equality with equals
while (iterator.hasNext()){
String obj = iterator.next();
if(obj.equals(e))
System.out.println("the object "+e+" exists in the list");
}
}
}
def exists in treeset? trueReferences:
eee exists in treeset? false
the def object exists in the list
StackOverFlow: How come Java's TreeSet has no get() method?
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...