集册 Java实例教程 检查元素是否存在列表

检查元素是否存在列表

欢马劈雪     最近更新时间:2020-01-02 10:19:05

421
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
列表中存在的检查元素

import java.util.ArrayList;// 来 自 nowjava


public class Main

{

   public static void main(String[] args)

   {

      // create a new ArrayList of Strings with an initial capacity of 10

      ArrayList<String> items = new ArrayList<String>(); 


      items.add("red"); // append an item to the list          

      items.add(0, "yellow"); // insert "yellow" at index 0


      // check if a value is in the List

      System.out.printf("\"red\" is %sin the list%n",

         items.contains("red") ? "": "not ");


      // display number of elements in the List

      System.out.printf("Size: %s%n", items.size());


      items.remove(1); // remove item at index 1/*来 自 n  o  w  j  a  v  a . c o m*/

      display(items, "Remove second list element (green):"); 


      // check if a value is in the List

      System.out.printf("\"red\" is %sin the list%n",

         items.contains("red") ? "": "not ");


      // display number of elements in the List

      System.out.printf("Size: %s%n", items.size());

   } 


   // display the ArrayList's elements on the console

   public static void display(ArrayList<String> item
展开阅读全文