2010-12-04 58 views
94

我有一個10個字符串ArrayList。如何使用另一個字符串值更新索引5如何更新ArrayList中某個位置的元素?

+6

很常見的問題,人們對Java的`的ArrayList <>值的有關名單`圖書館。 set(pos,val)方法的存在並不直觀,並且不適合其他Java範例。 – 2016-08-02 23:00:47

回答

210

arrListArrayListnewValueString,然後就去做:

arrList.set(5, newValue); 

這可以在Java API參考here找到。

22
list.set(5,"newString"); 
+0

我想你的意思是索引5,因爲ArrayList只有10個元素,這會炸掉。 ;) – 2010-12-04 09:53:18

11
arrList.set(5,newValue); 

,如果ü要更新它,然後加入這一行也

youradapater.NotifyDataSetChanged(); 
1

arrayList.set(位置,NEWVALUE); location =其中u wnna插入,newValue =您插入的新元素。

通知是可選的,取決於條件。

1
import java.util.ArrayList; 
import java.util.Iterator; 


public class javaClass { 

public static void main(String args[]) { 


    ArrayList<String> alstr = new ArrayList<>(); 
    alstr.add("khan"); 
    alstr.add("yogesh"); 
    alstr.add("kapil"); 
    alstr.add("rajoria"); 

    for(String str : alstr) { 
     System.out.println(str); 
    } 
    // update value here 
    alstr.set(3, "Ramveer"); 
    System.out.println("with Iterator"); 
    Iterator<String> itr = alstr.iterator(); 

    while (itr.hasNext()) { 
     Object obj = itr.next(); 
     System.out.println(obj); 

    } 
}} 
1
arrayList.set(5,newValue); 

arrayList是要更新和newValue是您要更換的第5個指標

相關問題