Java函数的使用案例及优化技巧
发布时间:2023-06-30 15:13:18
1. 用Java编写一个小程序,实现两个整数相加的功能。
public class AddTwoNumbers {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 3);
System.out.println("Sum: " + sum);
}
}
优化技巧:
- 可以使用可变参数的方式,实现对多个整数进行相加。
public class AddNumbers {
public static int add(int... numbers) {
int sum = 0;
for (int number : numbers) {
sum += number;
}
return sum;
}
public static void main(String[] args) {
int sum = add(5, 3, 2, 8);
System.out.println("Sum: " + sum);
}
}
2. 用Java编写一个方法,找到数组中的最大值。
public class FindMax {
public static int findMax(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("数组不能为空");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
public static void main(String[] args) {
int[] arr = {1, 5, 3, 8, 2};
int max = findMax(arr);
System.out.println("最大值: " + max);
}
}
优化技巧:
- 可以使用Java 8的流(stream)来实现找到数组中的最大值。
import java.util.Arrays;
public class FindMax {
public static int findMax(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("数组不能为空");
}
return Arrays.stream(arr)
.max()
.getAsInt();
}
public static void main(String[] args) {
int[] arr = {1, 5, 3, 8, 2};
int max = findMax(arr);
System.out.println("最大值: " + max);
}
}
这种方法使用了Arrays类的stream()方法将数组转换成流对象,然后使用max()方法找到流中的最大值,并使用getAsInt()方法获取最大值的整数表示。
3. 用Java编写一个方法,判断一个字符串是否是回文。
public class Palindrome {
public static boolean isPalindrome(String str) {
String reversedStr = new StringBuilder(str).reverse().toString();
return str.equals(reversedStr);
}
public static void main(String[] args) {
String str = "level";
boolean isPal = isPalindrome(str);
System.out.println(str + "是回文吗?" + isPal);
}
}
优化技巧:
- 可以使用双指针的方式,从字符串的两端向中间进行比较。
public class Palindrome {
public static boolean isPalindrome(String str) {
int i = 0;
int j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static void main(String[] args) {
String str = "level";
boolean isPal = isPalindrome(str);
System.out.println(str + "是回文吗?" + isPal);
}
}
这种方法不需要创建新的字符串对象,直接对原字符串进行比较,可以节省内存空间。同时,使用双指针的方式可以提高效率,仅需要进行一次遍历就可以得到结果。
以上是使用Java函数的案例及优化技巧,可以大大提高代码的可读性和性能。在实际的开发中,根据具体的需求场景选择合适的函数使用方式和优化技巧,可以提高开发效率和代码质量。
