欢迎访问宙启技术站
智能推送

Java集合框架中的查找函数的用法

发布时间:2023-06-14 03:17:24

Java集合框架是Java编程语言提供的一组类和接口,用于管理和组织对象的集合。Java集合框架包含了各种类型的集合,如List、Set、Map等,它们提供了一系列非常方便的方法来操作和访问集合中的元素。其中,查找函数是其中之一,提供了查找和检索集合中元素的方法。在本文中,我们将讨论Java集合框架中常用的查找函数的用法。

1. List集合中的查找函数

ArrayList和LinkedList是常见的List集合,它们提供了各种查找函数。常用的函数有:

(1) indexOf(Object o):返回集合中首次出现指定元素的索引,如果元素未找到,则返回-1。例如:

ArrayList<Integer> list = new ArrayList<>();

list.add(1);

list.add(2);

list.add(3);

int index = list.indexOf(2); // index = 1

(2) lastIndexOf(Object o):返回集合中最后出现指定元素的索引,如果元素未找到,则返回-1。例如:

ArrayList<Integer> list = new ArrayList<>();

list.add(1);

list.add(2);

list.add(2);

int index = list.lastIndexOf(2); // index = 2

(3) contains(Object o):判断集合中是否包含指定元素,如果存在则返回true,否则返回false。例如:

ArrayList<Integer> list = new ArrayList<>();

list.add(1);

list.add(2);

boolean isContain = list.contains(2); // isContain = true

2. Set集合中的查找函数

HashSet和TreeSet是常见的Set集合,它们提供了各种查找函数。常用的函数有:

(1) contains(Object o):同List集合中的该函数,用于判断集合中是否包含指定元素。

(2) isEmpty():如果集合为空,则返回true,否则返回false。例如:

HashSet<Integer> set = new HashSet<>();

boolean isEmpty = set.isEmpty(); // isEmpty = true

(3) size():返回集合中元素的数量。例如:

HashSet<Integer> set = new HashSet<>();

set.add(1);

set.add(2);

int size = set.size(); // size = 2

3. Map集合中的查找函数

HashMap和TreeMap是常见的Map集合,它们提供了各种查找函数。常用的函数有:

(1) containsKey(Object key):判断Map集合中是否包含指定键,如果存在则返回true,否则返回false。例如:

HashMap<String, Integer> map = new HashMap<>();

map.put("apple", 1);

map.put("banana", 2);

boolean isContain = map.containsKey("apple"); // isContain = true

(2) containsValue(Object value):判断Map集合中是否包含指定值,如果存在则返回true,否则返回false。例如:

HashMap<String, Integer> map = new HashMap<>();

map.put("apple", 1);

map.put("banana", 2);

boolean isContain = map.containsValue(2); // isContain = true

(3) get(Object key):返回指定键所映射的值,如果Map集合中不包含该键,则返回null。例如:

HashMap<String, Integer> map = new HashMap<>();

map.put("apple", 1);

map.put("banana", 2);

Integer value = map.get("apple"); // value = 1

综上所述,Java集合框架提供了丰富的查找函数,方便我们快速地查找、检索集合中的元素。根据具体场景和需求,我们可以选择不同的查找函数来操作我们的集合。