开发者

Searching through an ArrayList

I have an array list comprised of Objects. Each object is comprised开发者_JAVA技巧 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)?


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));
  }

}


ArrayList.indexOf(myString)

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜