JAVA:防止重复条目到 ArrayList [英] JAVA: Preventing Duplicate Entries to an ArrayList

查看:25
本文介绍了JAVA:防止重复条目到 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试防止将重复条目添加到 ArrayList,因为在读取文件的每一行时正在填充列表.文件的每一行都采用node1 node2"格式(制表符分隔符).这里的副本可能是node1 node2"或node2 node1".这是我尝试执行此操作的代码:

I am trying to prevent duplicate entries from being added to an ArrayList as the list is being populated whilst reading through each line of a file. Each line of the file is in the format "node1 node2" (tab delimiter). A duplicate here could either be "node1 node2" or "node2 node1". Here is my code to try and perform this operation:

while((line = bufferedReader.readLine()) != null) {

     String delimiter = "\t";
     String[] tempnodelist;  
     tempnodelist = line.split(delimiter);

     for (int i=0; i <= edgesnumber; i++) {   //edgesnumber = edges.size()

         if (tempnodelist[0] && tempnodelist[1] != edges.get(i)) {

             edges.add(line);

            }
        }

     nodes.add(tempnodelist[0]);  
     nodes.add(tempnodelist[1]); //intial intended use of tempnodelist.

}

由于我已经将每一行拆分为每个节点的 HashSet,因此我尝试使用它来检查重复项.目前我似乎无法正确使用语法.如何检查 ArrayList 的先前条目是否有重复项,并防止添加它们,同时继续填充 ArrayList?这段代码目前有什么问题?

Since I'm already splitting each line to make a HashSet of each node, I'm trying to use this to check for duplicates. At the moment I just can't seem to get the syntax right. How can I check through previous entries of the ArrayList for duplicates, and prevent them from being added, whist continuing to populate the ArrayList? what is wrong with this code currently?

如有不明白的地方,请提出任何问题,

Please ask any questions if anything is unclear,

提前致谢!

推荐答案

使用 LinkedHashSet 然后将其转换为 ArrayList,因为 LinkedHashSet 具有可预测的迭代顺序(插入顺序)并且它是一个 设置.

Use a LinkedHashSet and then convert it to an ArrayList, because a LinkedHashSet has a predictable iteration order (the insertion-order) and it is a Set.

例如

LinkedHashSet<String> uniqueStrings = new LinkedHashSet<String>();

uniqueStrings.add("A");
uniqueStrings.add("B");
uniqueStrings.add("B");
uniqueStrings.add("C");
uniqueStrings.add("A");

List<String> asList = new ArrayList<String>(uniqueStrings);
System.out.println(asList);

会输出

 [A, B, C]

这篇关于JAVA:防止重复条目到 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆