java表驱动各种类型示例
时间: 2023-06-29 09:07:44 浏览: 55
Java中的表驱动是一种常见的编程技术,它可以通过预先定义的数据表来简化代码。下面是一些示例,展示了如何使用表驱动技术来处理各种类型。
1. 处理字符串类型
示例代码:
```java
Map<String, String> table = new HashMap<>();
table.put("hello", "world");
table.put("goodbye", "cruel world");
String input = "hello";
String output = table.get(input);
System.out.println(output); // 输出:world
```
2. 处理枚举类型
示例代码:
```java
enum Color {
RED,
GREEN,
BLUE
}
Map<Color, String> table = new HashMap<>();
table.put(Color.RED, "#FF0000");
table.put(Color.GREEN, "#00FF00");
table.put(Color.BLUE, "#0000FF");
Color input = Color.RED;
String output = table.get(input);
System.out.println(output); // 输出:#FF0000
```
3. 处理数字类型
示例代码:
```java
Map<Integer, String> table = new HashMap<>();
table.put(1, "one");
table.put(2, "two");
table.put(3, "three");
int input = 2;
String output = table.get(input);
System.out.println(output); // 输出:two
```
4. 处理自定义类型
示例代码:
```java
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Map<String, Person> table = new HashMap<>();
table.put("Alice", new Person("Alice", 25));
table.put("Bob", new Person("Bob", 30));
String input = "Bob";
Person output = table.get(input);
System.out.println(output.getName() + " is " + output.getAge() + " years old."); // 输出:Bob is 30 years old.
```
这些示例展示了如何使用Java中的表驱动技术来处理不同类型的数据。无论是字符串、枚举、数字还是自定义类型,表驱动技术都可以帮助我们简化代码并提高代码的可读性。