Java函数用于在列表中查找给定元素的位置
Java中提供了许多内置函数,用于在列表中查找给定元素的位置。这些函数包含在ArrayList、LinkedList、Vector和Stack这些类中。
1. ArrayList的indexOf()函数
ArrayList是Java中非常常用的列表类之一,可以存储任何类型的对象。ArrayList的indexOf()函数用于查找给定元素在列表中 次出现的位置。如果列表中不存在该元素,则返回-1。
例如,下面的代码演示了如何使用indexOf()函数查找字符串“apple”在ArrayList中的位置:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("banana");
fruits.add("apple");
fruits.add("orange");
fruits.add("grape");
int index = fruits.indexOf("apple");
if (index == -1)
System.out.println("The fruit is not in the list.");
else
System.out.println("The fruit is at position " + index + ".");
}
}
输出结果为“The fruit is at position 1.”,证明字符串“apple”在ArrayList中的位置为1。
2. LinkedList的indexOf()函数
LinkedList是另一个Java中常用的列表类,与ArrayList类似,也可以存储任何类型的对象。LinkedList的indexOf()函数也可以用于查找给定元素在列表中 次出现的位置。
例如,下面的代码演示了如何使用LinkedList的indexOf()函数查找到字符串“apple”在LinkedList中的位置:
import java.util.LinkedList;
public class Example {
public static void main(String[] args) {
LinkedList<String> fruits = new LinkedList<String>();
fruits.add("banana");
fruits.add("apple");
fruits.add("orange");
fruits.add("grape");
int index = fruits.indexOf("apple");
if (index == -1)
System.out.println("The fruit is not in the list.");
else
System.out.println("The fruit is at position " + index + ".");
}
}
输出结果为“The fruit is at position 1.”,说明字符串“apple”在LinkedList中的位置为1。
3. Vector的indexOf()函数
Vector是与ArrayList类似的Java中的列表类,也可以存储任何类型的对象。Vector的indexOf()函数也用于查找给定元素在列表中 次出现的位置。如果列表中不存在该元素,则返回-1。
例如,下面的代码演示了如何使用Vector的indexOf()函数查找到字符串“apple”在Vector中的位置:
import java.util.Vector;
public class Example {
public static void main(String[] args) {
Vector<String> fruits = new Vector<String>();
fruits.add("banana");
fruits.add("apple");
fruits.add("orange");
fruits.add("grape");
int index = fruits.indexOf("apple");
if (index == -1)
System.out.println("The fruit is not in the list.");
else
System.out.println("The fruit is at position " + index + ".");
}
}
输出结果为“The fruit is at position 1.”,说明字符串“apple”在Vector中的位置为1。
4. Stack的search()函数
Stack是Java中的堆栈类,它实现了先进后出(FILO)的操作方式。Stack的search()函数用于查找给定元素在堆栈中的位置。该函数返回该元素在堆栈中从顶部数起的位置,如果找不到该元素,则返回-1。
例如,下面的代码演示了如何使用Stack的search()函数查找到字符串“apple”在堆栈中的位置:
import java.util.Stack;
public class Example {
public static void main(String[] args) {
Stack<String> fruits = new Stack<String>();
fruits.push("banana");
fruits.push("apple");
fruits.push("orange");
fruits.push("grape");
int index = fruits.search("apple");
if (index == -1)
System.out.println("The fruit is not in the stack.");
else
System.out.println("The fruit is at position " + index + ".");
}
}
输出结果为“The fruit is at position 2.”,说明字符串“apple”在堆栈中的位置为2。
总结
在Java中,可以使用ArrayList、LinkedList、Vector和Stack等类中的indexOf()函数和search()函数来查找列表中给定元素的位置。这些函数都返回元素在列表中的位置,如果找不到该元素,则返回-1。在使用这些函数时需要注意,这些函数都是从0开始计数的。
