在Java中,switch语句可以通过以下方法进行优化:
public enum Color {
RED, GREEN, BLUE;
}
Color color = Color.RED;
// 使用ordinal()方法
int index = color.ordinal();
switch (index) {
case 0:
// Do something for red
break;
case 1:
// Do something for green
break;
case 2:
// Do something for blue
break;
}
// 使用name()方法
String colorName = color.name();
switch (colorName) {
case "RED":
// Do something for red
break;
case "GREEN":
// Do something for green
break;
case "BLUE":
// Do something for blue
break;
}
public class Operation {
public static void add(int a, int b) {
// Do something for addition
}
public static void subtract(int a, int b) {
// Do something for subtraction
}
public static void multiply(int a, int b) {
// Do something for multiplication
}
public static void divide(int a, int b) {
// Do something for division
}
}
String operation = "add";
int a = 1;
int b = 2;
Map<String, Runnable> operations = new HashMap<>();
operations.put("add", () -> Operation.add(a, b));
operations.put("subtract", () -> Operation.subtract(a, b));
operations.put("multiply", () -> Operation.multiply(a, b));
operations.put("divide", () -> Operation.divide(a, b));
if (operations.containsKey(operation)) {
operations.get(operation).run();
} else {
// Do something for invalid operation
}
public abstract class Shape {
public abstract double getArea();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
Shape shape = new Circle(5);
System.out.println("Area: " + shape.getArea());
总之,根据具体情况选择合适的方法来优化switch语句,可以提高代码的可读性、可维护性和性能。