搜索ArrayList

时间:2011-03-25 01:23:15

标签: java arraylist

我有一个由Objects组成的数组列表。每个对象都由字符串组成。

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)

“第三个”对象是泵入ArrayList的内容。

如何在此ArrayList中搜索特定字符串,然后返回ArrayList的包含元素的索引(用于删除,显示等)?

3 个答案:

答案 0 :(得分:1)

这些对象究竟是什么? 它们是您定义的类吗? 如果是这样,你需要浏览你的对象数组,让每个对象都有一个.contains()方法,它应该有代码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));
  }

}

答案 1 :(得分:0)

答案 2 :(得分:0)

这是一个例子

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

这是输出:

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)

关键点是,每indexOf()次{}返回-1而不是index