简体   繁体   English

如何在Java中创建常规数据类型值的多重映射

[英]How to create multimap of general datatype value in Java

I want to create a multimap where value could be general data type. 我想创建一个多图,其中值可以是常规数据类型。 For eg: 例如:

  MultiMap<String,Integer> columnvalueMapList = new MultiMap<String,Integer>();

Here instead of integer, i want to make general data type. 在这里我不是整数,而是要使通用数据类型。 How can i do so? 我该怎么办?

You can use Object as a value type in a Map . 您可以将Object用作Map的值类型。 However this is rarely a good idea as you will likely end up needing instanceof and casts to make use of the objects you extract. 但是,这很少是一个好主意,因为您最终可能需要instanceof和cast来利用您提取的对象。

Often the motivation for this is to be able to store objects of different classes without a common superclass. 通常这样做的动机是能够存储没有通用超类的不同类的对象。 However a better option in these situations is to use an interface to define the common behaviour for all items in the collection. 但是,在这些情况下,更好的选择是使用interface来定义集合中所有项目的通用行为。 Then any classes that could be added to the collection must implement that interface. 然后,可以添加到集合中的所有类都必须实现该接口。 You then declare your collection as, for example, List<CommonInterface> . 然后,将您的集合声明为例如List<CommonInterface> This is safer, clearer and easier to understand. 这更安全,更清晰,更容易理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM