java treeset取值_Java TreeSet floor()用法及代碼示例

java.util.TreeSet類的floor()方法用於返回此集合中小於或等於給定元素的最大元素,如果沒有這樣的元素,則返回null。

用法:

public E floor(E e)

參數:該方法將值e作為要匹配的參數。

返回值:此方法返回小於或等於e的最大元素;如果沒有此類元素,則返回null

異常:如果指定元素為null且此集合使用自然順序,或者其比較器不允許使用null元素,則此方法將引發NullPointerException

以下示例說明了floor()方法

示例1:

// Java program to demonstrate

// floor() method

// for Integer value

import java.util.*;

public class GFG1 {

public static void main(String[] argv) throws Exception

{

try {

// create tree set object

TreeSet treeadd = new TreeSet();

// populate the TreeSet using add() method

treeadd.add(10);

treeadd.add(20);

treeadd.add(30);

treeadd.add(40);

// Print the TreeSet

System.out.println("TreeSet: " + treeadd);

// getting the floor value for 25

// using floor() method

int value = treeadd.floor(25);

// printing the floor value

System.out.println("Floor value for 25: "

+ value);

}

catch (NullPointerException e) {

System.out.println("Exception thrown : " + e);

}

}

}

輸出:

TreeSet: [10, 20, 30, 40]

Floor value for 25: 20

示例2:為NullPointerException

// Java program to demonstrate

// floor() method

// for NullPointerException

import java.util.*;

public class GFG1 {

public static void main(String[] argv)

throws Exception

{

try {

// create tree set object

TreeSet treeadd = new TreeSet();

// populate the TreeSet using add() method

treeadd.add(10);

treeadd.add(20);

treeadd.add(30);

treeadd.add(40);

// Print the TreeSet

System.out.println("TreeSet: " + treeadd);

// getting the floor value for null

// using floor() method

System.out.println("Trying to get"

+ " the floor value"

+ " for null");

int value = treeadd.floor(null);

// printing the floor value

System.out.println("Floor value for 25: "

+ value);

}

catch (NullPointerException e) {

System.out.println("Exception thrown : " + e);

}

}

}

輸出:

TreeSet: [10, 20, 30, 40]

Trying to get the floor value for null

Exception thrown : java.lang.NullPointerException

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值