2015-11-06 53 views
1

我想从输入文件中删除重复的名称并打印出所有名称只有一次。这里是我的代码:错误查找和删除java中的重复项

public static void main(String[] args) throws IOException { 
    ArrayList<String> fn = new ArrayList<String>(); 
    ArrayList<String> ln = new ArrayList<String>(); 
    ArrayList<String> names = new ArrayList<String>(); 
    getNames(fn,ln); 

    System.out.println("\n******* All Unique Names*********"); 
    remove(names); 
} 
public static int find(String s, ArrayList<String> a) { 
    for (int i = 0; i < a.size(); i++) 
     if (a.get(i).equals(s)) 
      return i;   
    return -1; 
} 
public static int remove(ArrayList<String>n){ 
    //int found = find(names, n); 
     int index = 0; 
    while (index < n.size() - 1) { 
     if (n.get(index).equals(n.get(index + 1))) { 
      n.remove(index + 1); 
     } else { 
      index++; 
     } 
    } 
    System.out.println(n); 
    return index; 
} 
} 

如何打印没有重复的名称?

+0

不'ArrayList'有'contains'方法? – Arc676

回答

1

你可以尝试使用HashSet而不是ArrayList。

将所有名称保存在HashSet中,并在完成保存后进行打印。这给你没有重复的名字。

+0

我不能在我的代码上使用HashSet,但谢谢! – yaya

+0

@yaya增加了另一个答案,如果这是有道理的,请接受答案.. – bakki

0

下面是一个例子,如何使用设置

  ArrayList<String> names = new ArrayList<String>(); 
     names.add("abc"); 
     names.add("bcd"); 
     names.add("abc"); 
     System.out.println("Names with duplicate : "); 
     System.out.println(names); 

     Set<String> uniqueNames = new HashSet<String>(names); 
     System.out.println("Names without duplicate : "); 
     System.out.println(uniqueNames); 

请试试这个删除重复的名字。 输出:

Names with duplicate : 
[abc, bcd, abc] 
Names without duplicate : 
[abc, bcd] 
+0

谢谢!但我不能在我的代码上使用HashSet @KhaiNo – yaya

+0

我可以知道原因吗? –

1

尝试这样

List<String> src = new ArrayList<String>(); 
    List<String> dest = new ArrayList<String>(); 
    for (String s : src) { 
     if (!dest.contains(s)) 
      dest.add(s); 
    } 

    System.out.println(dest); 
+0

@yaya我想帮你在这里不要做你的作业 – bakki

+0

图书馆关闭。必须搬到其他地方..我现在正在努力!我不断收到空括号打印出来 – yaya

+0

你必须添加数据到src列表否则你会得到括号..希望你明白.. – bakki