2014-10-27 49 views
0

如何將數據添加到String []或從String []中刪除行?從數組中添加或刪除數據

//excerpt from class 
public class Images { 

public final static String[] imageUrls = new String[]{ 
    "http://192.168.1.1/pictures/card/AA001a.jpg", 
    "http://192.168.1.1/pictures/card/AA001b.jpg"}; 
} 
+2

您可能想改爲使用'ArrayList'。只需調用add()和remove()即可完成。 – joao2fast4u 2014-10-27 16:08:19

回答

0

刪除項目:

public static String[] removeElements(String[] input, String deleteMe) { 
    List result = new LinkedList(); 

    for(String item : input) 
     if(!deleteMe.equals(item)) 
      result.add(item); 

    return result.toArray(input); 
} 

添加項目:

imageUrls.add("test1"); 
1

來源:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. 

相反,你可以使用一個VectorArrayList

一些示例代碼:

public static void main(String[] args) 
{ 
    // Inizialize a string: 
    String path = "http://192.168.1.1/pictures/card/AA001b.jpg"; 

    // Inizialize the ArrayList: 
    ArrayList<String> s = new ArrayList<String>(); 

    //Add some values: 
    s.add("http://192.168.1.1/pictures/card/AA001a.jpg"); 
    s.add("http://192.168.1.1/pictures/card/AA001b.jpg"); 

    //Remove first element: 
    s.remove(0); 

    //Remove the second element: 
    s.remove(path); 
} 
0

嘗試列表如下:

List<String> imageUrlList = Arrays.asList(imageUrls); 
imageUrlList.add("http://localhost/webapp/mypic.jpg"); 
imageUrlList.remove("http://192.168.1.1/pictures/card/AA001b.jpg");