Hello :)
Im using a textfield and a button to check if a certain object extist in a vector/hasmap, if it does the object will be displayed in a panel.
How do i pass the text in the vector / hashmap and search within it?
Printable View
Hello :)
Im using a textfield and a button to check if a certain object extist in a vector/hasmap, if it does the object will be displayed in a panel.
How do i pass the text in the vector / hashmap and search within it?
You don't pass anything into the collections, you loop through all the elements of each.
Say I had a Vector containing Song objects. And you searched by song titles.
Code:Vector songs = new Vector();
//add Song objects to vector
String search = "some user typed title";
for(int i=0; i<songs.size(); i++)
{
String title = ((Song)songs.get(i)).getTitle();
if (title.indexOf(search) > -1)
{
//the object you seek is at index "i"
break;
}
}
For your hashmap you have some unique "key" which is fed to a hashing function which tells you exactly where to look for the associated "value or object". If you are using the API's Hashmap, use the get() method, passing the key as the argument to the method. If the object is in the structure, you'll have the object returned, otherwise you receive a null.
For your program you'll have a unique key associated with each object. The event triggered by a button push will be passing the key associated with the object of interest to the Hashmap object's get() method. Then you need to handle the object returned.
Create a vector:
Add to vector:Code:Vector v = new Vector();
search for it:Code:v.add("mystring");
Create a hashmap:Code:if (v.contains("mystring")) System.out.println("found");
else System.out.println("NOT found");
add to hashmap:Code:Map m = new HashMap();
search for it:Code:m.put("mystring", "mystring");
by the way: i sugest to use a hashset for this purpose,Code:if (m.containsKey("mystring")) System.out.println("found");
else System.out.println("NOT found");
since you don't have to bother about a key, have maximum performance on search and you can be shure, every element exists only once (that's the principle of a set):
Code:Set s = new HashSet();
s.add("mystring");
if (s.contains("mystring")) System.out.println("found");
else System.out.println("NOT found");