Latest web development tutorials

Java 實例– List 元素替換

Java 實例 Java實例

以下實例演示瞭如何使用Collections 類的replaceAll() 來替換List中所有的指定元素:

/*
 author by w3cschool.cc
 Main.java
 */

import java.util.*;

public class Main {
   public static void main(String[] args) {
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      Collections.replaceAll(list, "one", "hundread");
      System.out.println("replaceAll: " + list);
   }
}

以上代碼運行輸出結果為:

List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]

Java 實例 Java實例