简体   繁体   English

将列表转换为int数组

[英]convert list into int array

i want get back the shuffled array of type integer, so i wrote this code but its not working... in this code i want new value each time of every object of class Scase... but that must from 5,50,100... 我想找回整数类型的随机数组,所以我写了这段代码,但是它不起作用...在这段代码中,我希望每次Scase类的每个对象都有新值...但这必须从5,50,100开始。 。

class Scase {

    int label;
    int value;

    public static int arr[] = {5,50,100};

    public static int[] toarr(List<Integer> list)
    {
        int[] ret = new int[list.size()];
        for (int i = 0; i < ret.length; i++)
            ret[i] = list.get(i);
        return ret;
    }

    public static void main(String args[])
    {
        Scase obj[] = new Scase[1];
        List<Integer> lst = new ArrayList<Integer>();

        lst = Arrays.asList(arr);

        Collections.shuffle(lst);

        int ar[];
        ar = toarr(lst);

        for(int i = 0; i <= 2; i++) {
            obj[i].value = ar[i];
        }
        System.out.println(obj[0].label + "  " + obj[0].value);
        System.out.println(obj[1].label + "  " + obj[1].value);
        System.out.println(obj[2].label + "  " + obj[2].value);
    }
}

Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. 不幸的是,由于Java处理原始类型,装箱,数组和泛型的性质,我不认为确实有更好的方法。 In particular: 尤其是:

List<T>.toArray won't work because there's no conversion from Integer to int You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery). List<T>.toArray不起作用,因为没有从Integer到int转换。您不能将int用作泛型的类型参数,因此它必须是int特定的方法(或使用反射进行操作的方法)令人讨厌的骗术)。 I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (ie there's a template which is copied for each type). 我相信有些库具有针对所有原始类型的这种方法的自动生成版本(即,有为每种类型复制的模板)。 It's ugly, but that's the way it is I'm afraid :( 这很丑,但是恐怕就是这样:(

Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays). 即使Arrays类在泛型到达Java之前就出现了,但如果今天引入它,它仍然必须包括所有可怕的重载(假设您要使用基本数组)。

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

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