在 Java 中查詢向量的最大元素


可以使用 java.util.Collections.max() 方法獲取向量的最大元素。此方法包含一個引數,即確定其最大元素的向量,並從向量返回最大元素。

展示這一點的程式如下所示 -

示例

 線上演示

import java.util.Collections;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(7);
      vec.add(3);
      vec.add(9);
      vec.add(5);
      vec.add(8);
      System.out.println("The Vector elements are: " + vec);
      System.out.println("The maximum element of the Vector is: " + Collections.max(vec));
   }
}

以上程式的輸出如下 -

The Vector elements are: [7, 3, 9, 5, 8]
The maximum element of the Vector is: 9

現在讓我們瞭解以上程式。

建立向量。然後使用 Vector.add() 將元素新增到向量。顯示向量。Collections.max() 用於查詢向量的最大元素並將其顯示。展示這一點的程式碼片段如下 -

Vector vec = new Vector();
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(5);
vec.add(8);
System.out.println("The Vector elements are: " + vec);
System.out.println("The maximum element of the Vector is: " + Collections.max(vec));

更新於: 30-6 月 -2020

962 次瀏覽

開啟你的職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.