Java一共有几个map_java – 在同一个键下有多个值的HashMap

你可以:

>使用具有列表作为值的地图。 Map< KeyType,List< ValueType>>。

>创建一个新的包装类,并将该包装的实例放在地图中。映射< KeyType,WrapperType&gt ;.

>使用像元组的类(保存创建大量的包装器)。 Map< KeyType,Tuple< Value1Type,Value2Type>>。

>并排使用多个地图。

例子

1.将列表映射为值

// create our map

Map> peopleByForename = new HashMap>();

// populate it

List people = new ArrayList();

people.add(new Person("Bob Smith"));

people.add(new Person("Bob Jones"));

peopleByForename.put("Bob", people);

// read from it

List bobs = peopleByForename["Bob"];

Person bob1 = bobs[0];

Person bob2 = bobs[1];

2.使用包装类

// define our wrapper

class Wrapper {

public Wrapper(Person person1, Person person2) {

this.person1 = person1;

this.person2 = person2;

}

public Person getPerson1 { return this.person1; }

public Person getPerson2 { return this.person2; }

private Person person1;

private Person person2;

}

// create our map

Map peopleByForename = new HashMap();

// populate it

Wrapper people = new Wrapper()

peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),

new Person("Bob Jones"));

// read from it

Wrapper bobs = peopleByForename["Bob"];

Person bob1 = bobs.Person1;

Person bob2 = bobs.Person2;

3.使用元组

// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map

Map peopleByForename = new HashMap>();

// populate it

peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",

new Person("Bob Jones"));

// read from it

Tuple bobs = peopleByForename["Bob"];

Person bob1 = bobs.Item1;

Person bob2 = bobs.Item2;

多个地图

// create our maps

Map firstPersonByForename = new HashMap();

Map secondPersonByForename = new HashMap();

// populate them

firstPersonByForename.put("Bob", new Person("Bob Smith"));

secondPersonByForename.put("Bob", new Person("Bob Jones"));

// read from them

Person bob1 = firstPersonByForename["Bob"];

Person bob2 = secondPersonByForename["Bob"];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值