首页 \ 问答 \ LinkedHashSet的HashSet不会删除具有多个元素的LinkedHashSet(HashSet of LinkedHashSets does not delete LinkedHashSet with multiple elements)

LinkedHashSet的HashSet不会删除具有多个元素的LinkedHashSet(HashSet of LinkedHashSets does not delete LinkedHashSet with multiple elements)

我正在学习数据结构和算法,并试图在Java中实现不相交的数据结构。 这是我的代码做同样的事情 -

import java.util.*;

public class DisjointSet<T> {
    Set<LinkedHashSet<T>> allSets;

    DisjointSet()   {
        allSets = new HashSet<LinkedHashSet<T>>();
    }

    public void makeSet(T t)    {
        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t))    {
                return;
            }
        }

        LinkedHashSet<T> set = new LinkedHashSet<T>();
        set.add(t);

        allSets.add(set);
    }

    public T findSet(T t)   {       
        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t))    {
                Iterator itr1 = set.iterator();
                T t1 = (T) itr1.next();
                return t1;
            }
        }

        return null;
    }

    public void union(T t1, T t2)   {
        LinkedHashSet<T> set1 = null, set2 = null;

        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t1))   {
                set1 = (LinkedHashSet<T>) set;
                System.out.println("Got set1:: " + set1);
            } else if (set.contains(t2))    {
                set2 = (LinkedHashSet<T>) set;
                System.out.println("Got set2:: " + set2);
            }
        }

        if (null != set1)   {
            System.out.println("Adding set2 to set1");
            set1.addAll(set2);

            if (null != set2)   {
                System.out.println("Removing set2");
                System.out.println(allSets.remove(set2));
            }
        }
    }

    public void viewAllSets()   {
        System.out.println(this.allSets);
    }
}

这是我正在运行的代码来测试我的实现 -

public class DisjointTest   {   
    public static void main(String [] args) {
        DisjointSet<Integer> dsets = new DisjointSet<Integer>();

        dsets.makeSet(30);
        dsets.makeSet(600);
        dsets.makeSet(20);
        dsets.makeSet(25);
        dsets.makeSet(90);
        dsets.makeSet(100);
        dsets.makeSet(1);

        dsets.viewAllSets();
        System.out.println();

        System.out.println(dsets.findSet(25));

        dsets.union(20, 25);
        dsets.viewAllSets();

        System.out.println();

        System.out.println(dsets.findSet(25));

        dsets.union(1, 100);
        dsets.viewAllSets();

        System.out.println();

        dsets.union(20, 100);
        dsets.viewAllSets();

        System.out.println(dsets.findSet(100));

        System.out.println();

        dsets.union(30, 90);
        dsets.viewAllSets();

        System.out.println();

        dsets.union(1, 90);
        dsets.viewAllSets();
    }   
}

当我尝试将一个集合与另一个集合,比如说set2,它有2个或更多元素时,集合会正确合并,但即使在调用allsets.remove(set2)之后,set2也不会从集合集合中删除

但是,如果要合并的集合,即; set2只有1个元素, allSets.remove(set2)成功地从集合集合中删除了set2。

以下是我的代码输出,证实了我的问题 -

[[1], [100], [20], [25], [600], [90], [30]]

25
Got set1:: [20]
Got set2:: [25]
Adding set2 to set1
Removing set2
true
[[1], [100], [20, 25], [600], [90], [30]]

20
Got set1:: [1]
Got set2:: [100]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25], [600], [90], [30]]

Got set2:: [1, 100]
Got set1:: [20, 25]
Adding set2 to set1
Removing set2
false
[[1, 100], [20, 25, 1, 100], [600], [90], [30]]
1

Got set1:: [20, 25, 1, 100]
Got set2:: [90]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25, 1, 100, 90], [600], [30]]

我无法理解为什么HashSet.remove(LinkedHashSet)无法删除具有多个元素的LinkedHashSet ,但成功删除了包含1个元素的LinkedHashSet

任何帮助将受到高度赞赏。 非常感谢你。


I am learning Data Strucrtures and Algorithms, and trying to implement disjoint-set data structure in Java. Here is my code to do the same-

import java.util.*;

public class DisjointSet<T> {
    Set<LinkedHashSet<T>> allSets;

    DisjointSet()   {
        allSets = new HashSet<LinkedHashSet<T>>();
    }

    public void makeSet(T t)    {
        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t))    {
                return;
            }
        }

        LinkedHashSet<T> set = new LinkedHashSet<T>();
        set.add(t);

        allSets.add(set);
    }

    public T findSet(T t)   {       
        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t))    {
                Iterator itr1 = set.iterator();
                T t1 = (T) itr1.next();
                return t1;
            }
        }

        return null;
    }

    public void union(T t1, T t2)   {
        LinkedHashSet<T> set1 = null, set2 = null;

        Iterator itr = allSets.iterator();
        while (itr.hasNext())   {
            LinkedHashSet set = (LinkedHashSet) itr.next();
            if (set.contains(t1))   {
                set1 = (LinkedHashSet<T>) set;
                System.out.println("Got set1:: " + set1);
            } else if (set.contains(t2))    {
                set2 = (LinkedHashSet<T>) set;
                System.out.println("Got set2:: " + set2);
            }
        }

        if (null != set1)   {
            System.out.println("Adding set2 to set1");
            set1.addAll(set2);

            if (null != set2)   {
                System.out.println("Removing set2");
                System.out.println(allSets.remove(set2));
            }
        }
    }

    public void viewAllSets()   {
        System.out.println(this.allSets);
    }
}

And here is the code I am running to test my implementation-

public class DisjointTest   {   
    public static void main(String [] args) {
        DisjointSet<Integer> dsets = new DisjointSet<Integer>();

        dsets.makeSet(30);
        dsets.makeSet(600);
        dsets.makeSet(20);
        dsets.makeSet(25);
        dsets.makeSet(90);
        dsets.makeSet(100);
        dsets.makeSet(1);

        dsets.viewAllSets();
        System.out.println();

        System.out.println(dsets.findSet(25));

        dsets.union(20, 25);
        dsets.viewAllSets();

        System.out.println();

        System.out.println(dsets.findSet(25));

        dsets.union(1, 100);
        dsets.viewAllSets();

        System.out.println();

        dsets.union(20, 100);
        dsets.viewAllSets();

        System.out.println(dsets.findSet(100));

        System.out.println();

        dsets.union(30, 90);
        dsets.viewAllSets();

        System.out.println();

        dsets.union(1, 90);
        dsets.viewAllSets();
    }   
}

When I try to merge a set with anther one, say set2, which has 2 or more elements, the sets get merged properly but set2 is not removed from the collection of sets even after calling allsets.remove(set2)

But, if the set to be merged, i.e; set2, has only 1 elements, allSets.remove(set2) successfully removes set2 from the collection of sets.

Here is the output of my code which confirms my problem-

[[1], [100], [20], [25], [600], [90], [30]]

25
Got set1:: [20]
Got set2:: [25]
Adding set2 to set1
Removing set2
true
[[1], [100], [20, 25], [600], [90], [30]]

20
Got set1:: [1]
Got set2:: [100]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25], [600], [90], [30]]

Got set2:: [1, 100]
Got set1:: [20, 25]
Adding set2 to set1
Removing set2
false
[[1, 100], [20, 25, 1, 100], [600], [90], [30]]
1

Got set1:: [20, 25, 1, 100]
Got set2:: [90]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25, 1, 100, 90], [600], [30]]

I am not able to comprehend why HashSet.remove(LinkedHashSet) is not able to remove a LinkedHashSet with multiple elements, but successfully removes a LinkedHashSet with 1 element.

Any help will be highly appreciated. Thank you very much.


原文:https://stackoverflow.com/questions/34454406
更新时间:2022-05-01 11:05

相关问答

更多
  • 选项: 1)您可以使用ftp_rawlist而不是ftp_nlist来获取文件/目录的完整列表,该文件/目录应该表明它是否是目录。 但是,该列表的格式将取决于ftp服务器的操作系统。 例如,在unix / linux系统上,原始列表可能如下所示: drwxrwxr-x 3 jm72 jm72 4096 Nov 2 16:39 myDir -rw-rw-r-- 1 jm72 jm72 257 Nov 2 16:39 myFile 第一列中的“d”会告诉你它是一个目录。 不确定它在Windows ...
  • Indy有一个TIdFTP组件,它有一个List()方法和一个DirectoryListing属性。 调用List()然后根据需要循环生成的DirectoryListing 。 DirectoryListing中的每个项目都会告诉您它是文件还是子文件夹。 如果需要索引整个系统,则必须在每个子文件夹的递归循环中调用List() 。 要记住的事情 - 今天互联网上的FTP服务器仍然使用了数百种特定于平台的目录列表格式。 原始FTP规范RFC 959中概述的LIST命令没有定义用于列表的任何格式,因此系统可以自由 ...
  • 这个函数只返回string array 。 您可以使用ftp_rawlist函数。 Documnetation 在这里你可以得到TYPE如下: $children = ftp_rawlist($connetion, $directory); foreach ($children as $child) { $chunks = preg_split("/\s+/", $child); $type=($chunks[0]{0} === 'd' ? 'directory' : 'file') ...
  • 怎么样: contents = ftp.retrlines('LIST') # List CWD contents securely. 要么: try: files = ftp.nlst() except ftplib.error_perm, resp: if str(resp) == "550 No files found": print("No files in this directory.") else: raise contents现在是该目录中可以调 ...
  • 好的,访问了很多网站,这里有一些你可能会找到的资源: 有关配置vsftpd的信息,请参阅这里有关如何安装,配置和使用的手册。 关于通过FTP递归接收多个文件,您可以使用wget (从此站点中提取): cd /tmp/ftptransfer wget --mirror --username=foo --password=bar ftp://ftp.originsite.com/path/to/folder 关于递归发送许多文件,许多人通过tar -n-send找到了这样做的唯一方法; 唯一的问题是文件将保持焦 ...
  • 你可以使用os.walk ,它返回一个路径,文件夹和文件的元组: files = next(os.walk('somedir'))[2] You could use os.walk, which returns a tuple of path, folders and files: files = next(os.walk('somedir'))[2]
  • 当我登录到正常的命令行客户端时,根本看不到您的作业目录。 当我ping服务器时,我得到的IP为204.62.251.180 。 如果你得到另一个,那么他们的服务器可能会有一些不一致。 我会联系NOAA CLASS关于这个,因为它似乎是他们的服务器的问题,而不是连接到他们的客户端。 When I log in to the normal command line client I don't see your job directory at all. When I ping the server I get ...
  • 您可以使用-exec选项查找对匹配的每个文件执行操作。 curl命令可用于上传文件: find / -type f -name '*.cpp' -exec curl -T {} ftp://somesite/somedir/ --user myname:mypassword \; You can use the -exec option to find to take action on every file matched. The curl command can be used to upload ...
  • 熟悉try-except块来处理这个问题: for ref in new_data: try: file = str(ref)+str('.jpg') ftpfile = urllib2.urlopen(ftp+file) localfile = open(file, 'wb') shutil.copyfileobj(ftpfile, localfile) except urllib2.URLError: print(" ...
  • 这不可能。 没有FTP命令列出系统上的所有ftp用户帐户,如果存在这样的命令,它也将被视为错误(安全性!),特别是如果它可用于未授权用户。 由于没有这样的命令存在,ftplib无法提供这样的命令。 您需要对计算机进行其他类型的(管理)访问,然后查看FTP服务器的配置以获取这些信息。 This is not possible. There is no FTP command to list all ftp user accounts on a system and it would also be consi ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)