设置交集

时间:2013-10-28 12:24:46

标签: java set

我想将inteserction(使用此方法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()hashCode()

3 个答案:

答案 0 :(得分:1)

这可以按预期工作(equals上的hashCodeConcept注意事项

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 + "]";
        }
    }
}

答案 1 :(得分:0)

首先,您需要在Concept类上覆盖equalshashcode方法。您不需要第三方库。只需使用

  set_1.retainAll(set2);

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

答案 2 :(得分:0)

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