gpt4 book ai didi

java - 在 HashSet 中使用并集和交集方法

转载 作者:行者123 更新时间:2023-12-01 04:45:35 24 4
gpt4 key购买 nike

我在使用自定义集 MySet、并集和相交的基本功能时遇到问题。程序编译没有错误,但只返回一个空集。

有人看出问题出在哪里吗?

public class MySet<E> extends TreeSet<E> {
Set<E> set;

public MySet(){
set = null;
}

public MySet(Set<E> set){
this.set = set;
}

public void union(Set<E> s){
set.addAll(s);
}

public void intersection(Set<E> s){
set.retainAll(s);
}


}

主要方法

public class TestSet {

public static void main(String[] args) throws FileNotFoundException{
File f1 = new File("courseList1.txt");
File f2 = new File("courseList2.txt");

Scanner scan1 = new Scanner(f1);
Scanner scan2 = new Scanner(f2);

Set<Coarse> set1 = new HashSet<Coarse>();
Set<Coarse> set2 = new HashSet<Coarse>();

MySet<Coarse> mySet = new MySet<Coarse>(set1);

String designator;
int number;

while(scan1.hasNext()){
designator = scan1.next();
number = scan1.nextInt();
set1.add(new Coarse(designator, number));
}

while(scan2.hasNext()){
designator = scan2.next();
number = scan2.nextInt();
set2.add(new Coarse(designator, number));
}

mySet.union(set2);
mySet.intersection(set2);

}
}

最佳答案

您似乎正在尝试实现组合并同时扩展树集,但这不是一个好的做法,您要么使用组合并实现 Set 接口(interface)(带有 TreeSet 的后端),要么扩展树集

扩展TreeSet

    class MySet<E> extends TreeSet<E> {
public void union(Set<E> s){
addAll(s);
}

public void intersection(Set<E> s){
retainAll(s);
}
}

使用组合

    class MySet<E> implements Set<E> {
private TreeSet<E> set;

public MySet(TreeSet<E> set) {
this.set = new TreeSet<>(set);
}

public void union(Set<E> s){
set.addAll(s);
}

public void intersection(Set<E> s){
set.retainAll(s);
}

@Override
public int size() {
return set.size();
}

@Override
public boolean isEmpty() {
return set.isEmpty();
}

@Override
public boolean contains(Object o) {
return set.contains(o);
}

@Override
public Iterator<E> iterator() {
return set.iterator();
}

@Override
public Object[] toArray() {
return set.toArray();
}

@Override
public <T> T[] toArray(T[] a) {
return set.toArray(a);
}

@Override
public boolean add(E e) {
return set.add(e);
}

@Override
public boolean remove(Object o) {
return set.remove(o);
}

@Override
public boolean containsAll(Collection<?> c) {
return set.containsAll(c);
}

@Override
public boolean addAll(Collection<? extends E> c) {
return set.addAll(c);
}

@Override
public boolean retainAll(Collection<?> c) {
return set.retainAll(c);
}

@Override
public boolean removeAll(Collection<?> c) {
return set.removeAll(c);
}

@Override
public void clear() {
set.clear();
}

@Override
public boolean equals(Object o) {
return set.equals(o);
}

@Override
public int hashCode() {
return set.hashCode();
}
}

关于java - 在 HashSet 中使用并集和交集方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com