2011-03-25 100 views
0

我有一個由對象組成的數組列表。每個對象都由字符串組成。通過ArrayList搜索

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的包含元素的索引(用於刪除,顯示等)?

+0

請發佈您的聯繫方式 – 2011-03-25 04:12:00

回答

1

究竟是這些對象呢? 他們是你定義的類嗎? 如果是這樣,你需要通過你的對象數組,並讓每個oject有。載有()方法,應該具備哪些代碼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)); 
    } 

} 
+0

是的,他們是定義類 – Jinx3y 2011-03-25 01:35:14

+0

你能提供一個例子嗎?基於此: – Jinx3y 2011-03-25 01:36:17

+0

當然,可以說你的數組被稱爲「數組」:) 看到我的編輯 – 2011-03-25 04:07:24

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