0

我想将插入(使用此方法http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html)应用于包含非原始对象的集合。我写了这段代码,但我知道交叉点是空的..

        Concept a = new Concept("Dog");
        Concept b = new Concept("Tree");
        Concept c= new Concept("Dog");
        HashSet<Concept> set_1 = new HashSet<Concept>();
        HashSet<Concept> set_2 = new HashSet<Concept>();

        set_1.add(a);
        set_1.add(b);
        set_1.add(c);
        SetView<Concept> inter = Sets.intersection(set_1,set_2);
        System.out.println(inter.size());  ----> I HAVE ZERO !!!

该类Concept仅包含 String 类型的私有成员以及 get 和 set 方法。我没有equals()and hashCode()

4

3 回答 3

1

这可以按预期工作(注意equalshashCodeon Concept

package com.stackoverflow.so19634761;

import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;

import java.util.Set;

public class ISect {
    public static void main(final String[] args) {
        final Concept a = new Concept("Dog");
        final Concept b = new Concept("Tree");
        final Concept c= new Concept("Dog");
        final Set<Concept> set1 = Sets.newHashSet(a);
        final Set<Concept> set2 = Sets.newHashSet(b, c);

        final SetView<Concept> inter = Sets.intersection(set1, set2);
        System.out.println(inter); // => [Concept [data=Dog]]
    }

    private static class Concept {

        private final String data;

        // below this point code was generated by eclipse.

        public String getData() {
            return data;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((data == null) ? 0 : data.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Concept other = (Concept) obj;
            if (data == null) {
                if (other.data != null)
                    return false;
            } else if (!data.equals(other.data))
                return false;
            return true;
        }

        public Concept(String data) {
            this.data = data;
        }   

        @Override
        public String toString() {
            return "Concept [data=" + data + "]";
        }
    }
}
于 2013-10-28T12:35:51.687 回答
0

首先,您需要在 Concept 类上重写equals和方法。hashcode您不需要第三方库。只需使用

  set_1.retainAll(set2);

set_1.retainAll(set2)将 set_1 转换为 set_1 和 set_2 的交集。(两个集合的交集是只包含两个集合共有的元素的集合。)。

于 2013-10-28T12:26:03.257 回答
0

您将概念放在集合中,而不是字符串 - 狗,树。你还需要覆盖概念类的哈希码和等于它才能工作

于 2013-10-28T12:27:36.747 回答