我们可以使用Java的泛型来解决这个问题。以下是一个示例程序,演示如何使用泛型打印出不同类中具有相同名称的对象类型的地图。
import java.util.*;
public class MapPrinter {
public static void printMap(Map map) {
for (Map.Entry entry : map.entrySet()) {
String key = entry.getKey();
T value = entry.getValue();
System.out.println(key + " = " + value);
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ", age " + age;
}
}
class Animal {
private String name;
private String species;
public Animal(String name, String species) {
this.name = name;
this.species = species;
}
@Override
public String toString() {
return name + " (" + species + ")";
}
}
class Main {
public static void main(String[] args) {
Map personMap = new HashMap<>();
personMap.put("Alice", new Person("Alice", 25));
personMap.put("Bob", new Person("Bob", 30));
Map animalMap = new HashMap<>();
animalMap.put("Fluffy", new Animal("Fluffy", "Cat"));
animalMap.put("Rover", new Animal("Rover", "Dog"));
System.out.println("Person map:");
MapPrinter.printMap(personMap);
System.out.println("\nAnimal map:");
MapPrinter.printMap(animalMap);
}
}
在上面的例子中,我们定义了一个泛型方法printMap
,它接受一个字符串键和一个类型为T
的值的映射。我们可以在Main
类中创建一个Map
对象,其中Person
和Animal
是值的类型。然后我们调用MapPrinter.printMap()
方法,传递我们创建的两个不同类型的地图。该程序将正确打印每个Map
对象中的数据。
输出:
Person map:
Alice = Alice, age 25
Bob = Bob, age 30
Animal map:
Fluffy = Fluffy (Cat)
Rover = Rover (Dog)
上一篇:不同类中的通用接口
下一篇:不同类中使用的指向同一实例的指针