从具有重复性的排序数组中创建未排序的集合时得到

问题描述 投票:-1回答:3

我正在使用带有一些重复值的排序数组,然后为了简单地删除重复性,我将每个值添加到集合中。当我从排序数组创建集合时,为什么我没有得到排序集?

这是我的代码:

Set<Integer> set = new HashSet<Integer>();

    for(int score: scores) 
        if(!(set.contains(score)))
            set.add(score);

    System.out.println(set);

分数是100 100 50 40 40 20 10

预期输出:[100, 50, 40, 20, 10]

实际输出:[50, 100, 20, 40, 10]

java arrays set redundancy
3个回答
1
投票

我看到您正在进行if(!(set.contains(score)))比较。那为什么不去清单呢?列表将保持插入顺序。

int scores[]= {100,100,50,40,40,20,10};
        List<Integer> list=new ArrayList<Integer>();

        for(int score: scores) 
            if(!(list.contains(score)))
                list.add(score);

        System.out.println(list);
    }

输出::

[100, 50, 40, 20, 10]


0
投票

如果要对集合进行排序,请使用TreeSet。 TreeSet是一个排序集实现,由Java默认提供。官方文档https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html中的更多信息

Set<Integer> set = new TreeSet<Integer>();

for(int score: scores) 
    //if(!(set.contains(score))) # this is not needed as set already handles duplicates
        set.add(score);

System.out.println(set);

-1
投票

HashSet使用元素的哈希存储元素。这给出了O(1)的复杂性。散列不保留元素的顺序。因此,您将获得的输出未排序。

© www.soinside.com 2019 - 2024. All rights reserved.