简体   繁体   English

将 Treeset (object []) 转换为 int[] 数组?

[英]Converting Treeset (object []) into an int[] array?

I am making a method to sort using Hashset/Treeset, however I am stopped when it comes to taking my Treeset and trying to return it back from the method.我正在制作一种使用 Hashset/Treeset 进行排序的方法,但是在获取我的 Treeset 并尝试从该方法返回它时,我停止了。 I know I could change the return type to Object[], but I was wondering if there was any way to keep the return type as an int[].我知道我可以将返回类型更改为 Object[],但我想知道是否有任何方法可以将返回类型保持为 int[]。

static int[] sortArrayWithHashset(int array[]) {
    HashSet<Integer> myHashSet = new HashSet<Integer>();
    for (int i = 0; i > array.length;i++) {
        myHashSet.add(array[i]);
    }

    TreeSet<Integer> myTreeSet = new TreeSet<Integer>();
    myTreeSet.addAll(myHashSet);
    //array = myTreeSet.toArray();
    return array;
}

To convert a collection into an array you can either use Stream IPA or create an array manually and populate it inside a loop.要将集合转换为数组,您可以使用 Stream IPA 或手动创建数组并将其填充到循环中。

public static int[] collectionToIntArray(Collection<Integer> source) {
        return source.stream()
                .mapToInt(Integer::intValue)
                .toArray();
    }
public static int[] collectionToIntArray(Collection<Integer> source) {
        int[] result = new int[source.size()];
        int pos = 0;
        for (int next: source) {
            result[pos++] = next;
        }
        return result;
    }

The code you've provided is slightly contrived.您提供的代码有点做作。 There are things you need to be aware of:您需要注意以下几点:

  • Set will discard all duplicates from the source array; Set 将丢弃源数组中的所有重复项;
  • you can array elements into TreeSet directly;您可以将元素直接排列到 TreeSet 中;
  • write your code against interfaces not against class, that provides more flexibility, like that针对接口而不是针对 class 编写代码,这样可以提供更大的灵活性,例如
    Set<Integer> myHashSet = new HashSet<>();
    NavigableSet<Integer> myTreeSet = new TreeSet<>();
  • Lastly, I guess you were practicing in order to get familiar with the Set interface implementations and hence didn't aim for this code to be efficient.最后,我猜你是为了熟悉 Set 接口实现而练习的,因此并没有让这段代码变得高效。 To complete to overall picture it is worth reminding that to sort an array you can simply use Arrays.sort() .为了完成整体情况,值得提醒的是,您可以简单地使用Arrays.sort()对数组进行排序。

To get an int[] , what you must to is to write要获得int[] ,您必须编写

myTreeSet.stream().mapToInt(i -> i).toArray();

You can achieve the same without a Set using streams :您可以在没有Set的情况下使用streams实现相同的目的:

public static int[] sortArray(int[] array) {
    return Arrays.stream(array).sorted().toArray();
}

You code has a few bugs, for example:您的代码有一些错误,例如:

for (int i = 0; i > array.length;i++) {...}

This will cause and endless loop, correctly should be: i < array.length .这将导致无限循环,正确地应该是: i < array.length In fact this for loop can be transformed into an enhanced for , such as:实际上这个for循环可以转化为增强for ,例如:

HashSet<Integer> myHashSet = new HashSet<>();
for (int a : array) {
    myHashSet.add(a);
}

If we think about, this HashSet is not really needed, since we can add everything directly to the TreeSet .如果我们考虑一下,这个HashSet并不是真正需要的,因为我们可以将所有内容直接添加到TreeSet

Moving on, the problem with using toArray and expecting to have an array with primitive integers, will not work.继续前进,使用toArray并期望有一个原始整数数组的问题将不起作用。 The reason for this is that collections in Java can store types which inherit Object .原因是 Java 中的 collections 可以存储继承Object的类型。 To be able to store primitive, we have boxed types, such as Integer , Double , etc. which wrap their primitive.为了能够存储原语,我们有包装它们的原语的盒装类型,例如IntegerDouble等。 So, if we want to use toArray , one option would be to return an array with Integers :因此,如果我们想使用toArray ,一种选择是返回一个带有Integers的数组:

static Integer[] sortArrayWithHashset(int[] array) {
    Set<Integer> myTreeSet = new TreeSet<>();
    for (int a : array) {
        myTreeSet.add(a);
    }

    return myTreeSet.toArray(new Integer[array.length]);
}

If we want to return an array of primitive integers, we can use streams to unbox the values, such as:如果我们想返回一个原始整数数组,我们可以使用流来拆箱值,例如:

static int[] sortArrayWithHashset(int[] array) {
    Set<Integer> myTreeSet = new TreeSet<>();
        for (int a : array) {
            myTreeSet.add(a);
        }

    return myTreeSet.stream().mapToInt(i -> i).toArray();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM