我的逻辑困惑了。我只是想找出一种方法,而不使用HashSet删除ArrayList中的重复项。

public static void main(String[] args) {
    ArrayList<String> wordDulicate = new ArrayList<String>();
    wordDulicate.add("Tom");
    wordDulicate.add("Jones");
    wordDulicate.add("Sam");
    wordDulicate.add("Jamie");
    wordDulicate.add("Robie");
    wordDulicate.add("Helen");
    wordDulicate.add("Tom");
    wordDulicate.add("Troy");
    wordDulicate.add("Mika");
    wordDulicate.add("Tom");

    for (String dupWord : wordDulicate) {
        if (wordDulicate.equals(dupWord))
            System.out.println(wordDulicate.get(dupWord));
    }
}

最佳答案

这种方法需要另一个 list :

       ArrayList<String> wordDulicate = new ArrayList<String>();

        wordDulicate.add("Tom");
        wordDulicate.add("Jones");
        wordDulicate.add("Sam");
        wordDulicate.add("Jamie");
        wordDulicate.add("Robie");
        wordDulicate.add("Helen");
        wordDulicate.add("Tom");
        wordDulicate.add("Troy");
        wordDulicate.add("Mika");
        wordDulicate.add("Tom");

        ArrayList<String> nonDupList = new ArrayList<String>();

        Iterator<String> dupIter = wordDulicate.iterator();
        while(dupIter.hasNext())
        {
        String dupWord = dupIter.next();
        if(nonDupList.contains(dupWord))
        {
            dupIter.remove();
        }else
        {
            nonDupList.add(dupWord);
        }
        }
      System.out.println(nonDupList);

输出:
[Tom, Jones, Sam, Jamie, Robie, Helen, Troy, Mika]

关于java - 在不使用HashSet的情况下删除ArrayList中的重复元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12697202/

10-10 21:37