不同类中具有相同名称的对象类型的地图如何打印的通用方法?
创始人
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)

相关内容

热门资讯

第6分钟辅助!uupoker透... 第6分钟辅助!uupoker透视,wepoker有辅助吗,攻略教程(有挂工具)1、起透看视 wepo...
7分钟辅助!德普之星透视辅助软... 7分钟辅助!德普之星透视辅助软件激活码,werplan外卦神器,法门教程(有挂辅助)1、德普之星透视...
第六分钟辅助!德普之星有透视辅... 第六分钟辅助!德普之星有透视辅助吗,约局吧德州透视,积累教程(确实有挂)1、许多玩家不知道德普之星有...
第5分钟辅助!德普之星透视辅助... 第5分钟辅助!德普之星透视辅助,wepoker透视最简单三个步骤,办法教程(确实有挂)1、完成wep...
七分钟辅助!安装不了wepok... 七分钟辅助!安装不了wepoker,uupoker透视,要领教程(新版有挂)1、玩家可以在安装不了w...
第5分钟辅助!佛手大菠萝辅助,... 第5分钟辅助!佛手大菠萝辅助,wejoker开挂,积累教程(有挂方法)第5分钟辅助!佛手大菠萝辅助,...
第2分钟辅助!hhpoker哪... 第2分钟辅助!hhpoker哪个俱乐部靠谱,sohoopoker辅助,法门教程(确实有挂)1、任何h...
1分钟辅助!wepoker破解... 1分钟辅助!wepoker破解是真的还是假的,wepoker辅助器是真的吗,学习教程(有挂助手)所有...
三分钟辅助!wepoker网页... 三分钟辅助!wepoker网页版透视方法,hhpoker脚本,妙招教程(讲解有挂)1、完成wepok...
7分钟辅助!大菠萝免费辅助,w... 7分钟辅助!大菠萝免费辅助,wpk透视是真的假的,总结教程(有挂讲解)1、进入游戏-大厅左侧-新手福...