集册 Java实例教程 汇总通用ArrayList中的数字

汇总通用ArrayList中的数字

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

581
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
汇总通用ArrayList中的数字


import java.util.ArrayList;

/**
时 代      J a v a   公   众 号 - nowjava.com 提供 
**/

public class Main

{

   public static void main(String[] args) 

   {

      Number[] numbers = {1, 2.4, 3, 4.1}; // Integers and Doubles

      ArrayList<Number> numberList = new ArrayList<>();


      for (Number element : numbers) 

         numberList.add(element); // place each number in numberList


      System.out.printf("numberList contains: %s%n", numberList);

      System.out.printf("Total of the elements in numberList: %.1f%n", 

         sum(numberList));

   }


   // calculate total of ArrayList elements

   public static double sum(ArrayList<Number> list)

   {

      double total = 0; // initialize total
      /**
       * n o w j a   v  a . c o m - 时  代 
展开阅读全文