Java数组面试题
1. 创建一个包含多个元素的数组,并打印输出数组的内容。
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};for (String element : array) {System.out.println(element);}}
}
2. 如何访问数组中的特定元素?
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};System.out.println(array[1]); // 输出:banana}
}
3. 如何向数组中添加新的元素?
Java中的数组长度是固定的,无法直接添加新的元素。需要创建一个新数组,并将旧数组中的元素复制到新数组中。
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};String[] newArray = new String[array.length + 1];System.arraycopy(array, 0, newArray, 0, array.length);newArray[array.length] = "grape";for (String element : newArray) {System.out.println(element);}}
}
4. 如何检查数组中是否存在指定的元素?
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};boolean exists = false;for (String element : array) {if (element.equals("banana")) {exists = true;break;}}if (exists) {System.out.println("存在");} else {System.out.println("不存在");}}
}
5. 如何在数组中搜索指定元素,并返回对应的索引?
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};int index = -1;for (int i = 0; i < array.length; i++) {if (array[i].equals("banana")) {index = i;break;}}System.out.println(index); // 输出:1}
}
6. 如何遍历数组并输出每个元素?
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};for (String element : array) {System.out.println(element);}}
}
7. 如何获取数组的长度(即元素的个数)?
public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};int length = array.length;System.out.println(length); // 输出:3}
}
8. 如何按照字母顺序对数组进行排序?
import java.util.Arrays;public class Main {public static void main(String[] args) {String[] array = {"apple", "banana", "orange"};Arrays.sort(array);for (String element : array) {System```javaSystem.out.println(element);}}
}
9. 如何计算数组中所有元素的总和?
public class Main {public static void main(String[] args) {int[] array = {1, 2, 3, 4, 5};int sum = 0;for (int element : array) {sum += element;}System.out.println(sum); // 输出:15}
}
10. 如何查找数组中的最大值和最小值?
import java.util.Arrays;public class Main {public static void main(String[] args) {int[] array = {5, 2, 9, 1, 7};Arrays.sort(array);int min = array[0];int max = array[array.length - 1];System.out.println("最小值:" + min); // 输出:1System.out.println("最大值:" + max); // 输出:9}
}