不同类中具有相同名称的对象类型的地图如何打印的通用方法?
创始人
2025-01-09 09:00:40
0

我们可以使用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对象,其中PersonAnimal是值的类型。然后我们调用MapPrinter.printMap()方法,传递我们创建的两个不同类型的地图。该程序将正确打印每个Map对象中的数据。

输出:

Person map:
Alice = Alice, age 25
Bob = Bob, age 30

Animal map:
Fluffy = Fluffy (Cat)
Rover = Rover (Dog)

相关内容

热门资讯

透视代打!aapoker插件下... 透视代打!aapoker插件下载(透视)aapoker破解侠是真的吗,微扑克教程(有挂技巧)1、很好...
透视美元局!wepoker透视... 透视美元局!wepoker透视脚本视频,wepoker代打辅助机器人(详细黑侠辅助器正版下载);1、...
透视代打!poker辅助器免费... 透视代打!poker辅助器免费安装,wepoker破解工具(详细黑侠辅助器正版下载)1、poker辅...
透视透视!aapoker安装包... 透视透视!aapoker安装包怎么使用(透视)aapoker公共底牌,可靠技巧(有挂辅助)一、aap...
透视玄学!aapoker辅助器... 透视玄学!aapoker辅助器是真的吗(透视)aapoker辅助软件合法吗,玩家教你(有挂解密);1...
辅助透视!wepoker买脚本... 辅助透视!wepoker买脚本靠谱吗,wepoker免费脚本咨询(详细有透视方法)1、进入到wepo...
透视存在!wepoker正确养... 透视存在!wepoker正确养号方法,wepoker究竟有没有透视(详细数据分析)一、wepoker...
透视系统!aapoker透视脚... 透视系统!aapoker透视脚本(透视)aapoker脚本怎么用,必赢教程(有挂教程)1、构建自己的...
透视有挂!wepoker手机插... 透视有挂!wepoker手机插件,wepoker免费脚本咨询(详细-h5下载);一、wepoker免...
透视黑科技!aapoker怎么... 透视黑科技!aapoker怎么设置提高好牌几率(透视)aapoker ai插件,曝光教程(有挂解说)...