java 没有get set,为什么java.util.HashSet没有get(Object o)方法?

I've seen other questions about getting objects from Set's based on index value and I understand why that is not possible. But I haven't been able to find a good explanation for why a get by object is not allowed so thought I would ask.

HashSet is backed by a HashMap so getting an object from it should be pretty straightforward. As it is now, it appears I would have to iterate over each item in the HashSet and test for equality which seems unnecessary.

I could just use a Map but I have no need for a key:value pair, I just need a Set.

For example say I have Foo.java:

package example;

import java.io.Serializable;

public class Foo implements Serializable {

String _id;

String _description;

public Foo(String id){

this._id = id

}

public void setDescription(String description){

this._description = description;

}

public String getDescription(){

return this._description;

}

public boolean equals(Object obj) {

//equals code, checks if id's are equal

}

public int hashCode() {

//hash code calculation

}

}

and Example.java:

package example;

import java.util.HashSet;

public class Example {

public static void main(String[] args){

HashSet set = new HashSet();

Foo foo1 = new Foo("1");

foo1.setDescription("Number 1");

set.add(foo1);

set.add(new Foo("2"));

//I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want.

Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed?

System.out.println(theFoo.getDescription); //Should print Number 1

}

}

Is it because the equals method is meant to test for "absolute" equality rather than "logical" equality (in which case contains(Object o) would be sufficient)?

解决方案

A Set is a Collection of objects which treats a.equals(b) == true as duplicates, so it doesn't make sense to try to get the same object you already have.

If you are trying to get(Object) from a collection, a Map is likely to be more appropriate.

What you should write is

Map map = new LinkedHashMap<>();

map.put("1", "Number 1");

map.put("2", null);

String description = set.get("1");

if an object is not in the set (based on equals), add it, if it is in the set (based on equals) give me the set's instance of that object

In the unlikely event you need this you can use a Map.

Map map = // LinkedHashMap or ConcurrentHashMap

Bar bar1 = new Bar(1);

map.put(bar1, bar1);

Bar bar1a = map.get(new Bar(1));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值