Reputation: 53
I have an array list comprised of Objects. Each object is comprised of Strings.
object first = (String a,String b,String c)
object second = (String d,String e,String f,String g)
object third = (first,second,String h,String i)
the "third" object is what is pumped into the ArrayList.
How do I search through this ArrayList for a specific string and then return the index of the containing element of the ArrayList (for deletion, display, etc)?
Upvotes: 0
Views: 3693
Reputation: 53
Here is an example
import java.io.FileNotFoundException;
public class AddressBook {
public static void main(String[] args) throws FileNotFoundException {
// new AddressBookGUI();
ContactBook c = new ContactBook();
c.readFromFile("input.txt");
System.out.println(c.getContact(0));
System.out.println(c.getContact(1));
System.out.println(c.getContact(2));
System.out.println(c.getContact(3));
System.out.println(c.getContact(4));
System.out.println(c.contactList.indexOf("Last"));
}
}
Here is the output:
run:
Last:First:MI:Street:City:State:ZipCode:HomePhone:CellPhone
Anderson:Robert:M.:19 AnyStreet:AnyCity:AnyTown:12345:(123)456-7890:(987)654-3210
MacLean:Jerry:A.:34th Ave West, #12:Brooklyn:NY:66978:(447)582-9943:(447)221-7735
LastName:First:MI:Street:City:State:ZipCode:HomePhone:CellPhone
Macintosh:Jerry:A.:34th Ave West, #12:Brooklyn:NY:66978:(447)582-9943:(447)221-7735
-1
BUILD SUCCESSFUL (total time: 0 seconds)
Key point is that every indexOf()
returns -1
instead of the index
.
Upvotes: 0
Reputation: 841
What are these objects exactly? Are they Classes that you defined? If so, you need to go through your Object Array, and have each oject have a .contains() method, which should have the code ArrayList.indexOf(myString)
for(int i=0; i<array.size(); i++)
{
Object o=array.get(i);
if(o.contains("STRING"){
//do code
}
}
class Object{
public boolean contains(String s){
return (array.contains(s));
}
}
Upvotes: 1
Reputation: 15028
ArrayList.indexOf(myString)
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
Upvotes: 0