Java TreeSet last() 方法



描述

Java TreeSet last() 方法用於返回此集合中當前的最後一個(最大)元素。

宣告

以下是 java.util.TreeSet.last() 方法的宣告。

public E last()

引數

返回值

方法呼叫返回此集合中當前的最後一個(最大)元素。

異常

NoSuchElementException − 如果此集合為空,則丟擲此異常。

獲取整數 TreeSet 的最後一個元素示例

以下示例演示瞭如何使用 Java TreeSet last() 方法來獲取此集合中當前的最後一個(最大)元素。我們建立了一個 Integer 型別的 TreeSet 物件。使用 add() 方法添加了一些條目,並使用 last() 方法檢索並列印最後一個/最大的元素。

package com.tutorialspoint;

import java.util.TreeSet;

public class TreeSetDemo {
   public static void main(String[] args) {

      // creating a TreeSet 
      TreeSet<Integer> treeset = new TreeSet<>();

      // adding in the tree set
      treeset.add(1);
      treeset.add(13);
      treeset.add(17);
      treeset.add(2);

      // displaying the last highest element
      System.out.println("Last highest element: "+treeset.last());    
   }    
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。

Last highest element: 17 

獲取字串 TreeSet 的最後一個元素示例

以下示例演示瞭如何使用 Java TreeSet last() 方法來獲取此集合中當前的最後一個(最大)元素。我們建立了一個 String 型別的 TreeSet 物件。使用 add() 方法添加了一些條目,並使用 last() 方法檢索並列印最後一個/最大的元素。

package com.tutorialspoint;

import java.util.TreeSet;

public class TreeSetDemo {
   public static void main(String[] args) {

      // creating a TreeSet 
      TreeSet<String> treeset = new TreeSet<>();

      // adding in the tree set
      treeset.add("A");
      treeset.add("D");
      treeset.add("C");
      treeset.add("B");

      // displaying the last highest element
      System.out.println("Last highest element: "+treeset.last());    
   }    
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。

Last highest element: D 

獲取物件 TreeSet 的最後一個元素示例

以下示例演示瞭如何使用 Java TreeSet last() 方法來獲取此集合中當前的最後一個(最大)元素。我們建立了一個 Student 型別的 TreeSet 物件。使用 add() 方法添加了一些條目,並使用 last() 方法檢索並列印最後一個/最大的元素。

package com.tutorialspoint;

import java.util.TreeSet;

public class TreeSetDemo {
   public static void main(String[] args) {

      // creating a TreeSet 
      TreeSet<Student> treeset = new TreeSet<>();

      // adding in the tree set
      treeset.add(new Student(1, "Robert"));
      treeset.add(new Student(2, "Julie"));
      treeset.add(new Student(3, "Adam"));
      treeset.add(new Student(4, "Julia"));

      // displaying the last highest element
      System.out.println("Last highest element: "+treeset.last());    
   }    
}
class Student implements Comparable<Student> {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
   
   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj;
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name);
   }

   @Override
   public int compareTo(Student student) {
      return this.rollNo - student.rollNo;
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果。

Last highest element: [ 4, Julia ]
java_util_treeset.htm
廣告
© . All rights reserved.