如何在 Java 中将 int[] 转换为 Integer[]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/880581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:35:53  来源:igfitidea点击:

How to convert int[] to Integer[] in Java?

javaarraysgenericscollections

提问by

I'm new to Java and very confused.

我是 Java 新手,非常困惑。

I have a large dataset of length 4 int[]and I want to count the number of times that each particular combination of 4 integers occurs. This is very similar to counting word frequencies in a document.

我有一个长度为 4 的大型数据集,int[]我想计算 4 个整数的每个特定组合出现的次数。这与计算文档中的词频非常相似。

I want to create a Map<int[], double>that maps each int[] to a running count as the list is iterated over, but Map doesn't take primitive types.

我想创建一个Map<int[], double>在迭代列表时将每个 int[] 映射到运行计数,但 Map 不采用原始类型。

so I made Map<Integer[], Double>

所以我做了 Map<Integer[], Double>

my data is stored as an ArrayList<int[]>so my loop should be something like

我的数据存储为一个ArrayList<int[]>所以我的循环应该是这样的

ArrayList<int[]> data = ... // load a dataset`

Map<Integer[], Double> frequencies = new HashMap<Integer[], Double>();

for(int[] q : data) {

    // **DO SOMETHING TO convert q from int[] to Integer[] so I can put it in the map

    if(frequencies.containsKey(q)) {
    frequencies.put(q, tfs.get(q) + p);
    } else {
        frequencies.put(q, p);
    }
}

I'm not sure what code I need at the comment to make this work to convert an int[]to an Integer[]. Or maybe I'm fundamentally confused about the right way to do this.

我不确定在评论中需要什么代码才能使这项工作将 an 转换int[]Integer[]. 或者也许我从根本上对正确的方法感到困惑。

回答by Mihai Toader

you don't need. int[]is an object and can be used as a key inside a map.

你不需要。int[]是一个对象,可以用作地图内的键。

Map<int[], Double> frequencies = new HashMap<int[], Double>();

is the proper definition of the frequencies map.

是频率图的正确定义。

This was wrong :-). The proper solution is posted too :-).

这是错误的:-)。也发布了正确的解决方案:-)。

回答by Eddie

If you want to convert an int[]to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:

如果您想将 an 转换int[]为 an Integer[],则在 JDK 中没有自动执行此操作的方法。但是,您可以执行以下操作:

int[] oldArray;

... // Here you would assign and fill oldArray

Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

If you have access to the Apache langlibrary, then you can use the ArrayUtils.toObject(int[])method like this:

如果您有权访问Apache lang库,则可以使用如下ArrayUtils.toObject(int[])方法:

Integer[] newArray = ArrayUtils.toObject(oldArray);

回答by Tom Hawtin - tackline

Presumably you want the key to the map to match on the value of the elements instead of the identity of the array. In that case you want some kind of object that defines equalsand hashCodeas you would expect. Easiest is to convert to a List<Integer>, either an ArrayListor better use Arrays.asList. Better than that you can introduce a class that represents the data (similar to java.awt.Rectanglebut I recommend making the variables private final, and the class final too).

大概您希望映射的键匹配元素的值而不是数组的标识。在这种情况下,您需要某种定义equalshashCode符合您期望的对象。最简单的方法是转换为 a List<Integer>,或者 anArrayList或者更好的使用Arrays.asList。比这更好的是,您可以引入一个表示数据的类(类似于java.awt.Rectangle但我建议将变量设为私有 final,类也是 final)。

回答by Mihai Toader

I was wrong in a previous answer. The proper solution is to use this class as a key in the map wrapping the actual int[].

我在之前的回答中错了。正确的解决方案是使用此类作为包装实际 int[] 的映射中的键。

public class IntArrayWrapper {
        int[] data;

        public IntArrayWrapper(int[] data) {
            this.data = data;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            IntArrayWrapper that = (IntArrayWrapper) o;

            if (!Arrays.equals(data, that.data)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return data != null ? Arrays.hashCode(data) : 0;
        }
    }

and change your code like this:

并像这样更改您的代码:

   Map<IntArrayWrapper, Double > freqs = new HashMap<IntArrayWrapper, Double>();

    for (int[] data : datas) {
        IntArrayWrapper wrapper = new IntArrayWrapper(data);

        if ( freqs.containsKey(wrapper)) {
            freqs.put(wrapper, freqs.get(wrapper) + p);
        }

        freqs.put(wrapper, p);
    }

回答by Chris

Rather than write your own code you can use an IntBuffer to wrap the existing int[] without having to copy the data into an Integer array

您可以使用 IntBuffer 包装现有的 int[] 而不必编写自己的代码,而不必将数据复制到 Integer 数组中

int[] a = {1,2,3,4};
IntBuffer b = IntBuffer.wrap(a);

IntBuffer implements comparable so you are able to use the code you already have written. Formally maps compare keys such that a.equals(b) is used to say two keys are equal, so two IntBuffers with array 1,2,3 - even if the arrays are in different memory locations - are said to be equal and so will work for your frequency code.

IntBuffer 实现了可比较的,因此您可以使用您已经编写的代码。正式映射比较键,这样 a.equals(b) 用于表示两个键相等,因此两个具有数组 1,2,3 的 IntBuffers - 即使数组位于不同的内存位置 - 被称为相等,因此将为您的频率代码工作。

ArrayList<int[]> data = ... // load a dataset`

Map<IntBuffer, Double> frequencies = new HashMap<IntBuffer, Double>();

for(int[] a : data) {

    IntBuffer q = IntBuffer.wrap(a);

    if(frequencies.containsKey(q)) {
        frequencies.put(q, tfs.get(q) + p);
    } else {
        frequencies.put(q, p);
    }

}

}

Hope that helps

希望有帮助

回答by Thomas Ahle

Update:Though the below compiles, it throws a ArrayStoreExceptionat runtime. Too bad. I'll let it stay for future reference.

更新:虽然下面编译,但它ArrayStoreException在运行时抛出 a 。太糟糕了。我会留着以备将来参考。



Converting an int[], to an Integer[]:

int[], 转换为Integer[]

int[] old;
...
Integer[] arr = new Integer[old.length];
System.arraycopy(old, 0, arr, 0, old.length);

I must admit I was a bit surprised that this compiles, given System.arraycopybeing lowlevel and everything, but it does. At least in java7.

我必须承认,考虑System.arraycopy到低级和所有内容,我对它的编译感到有些惊讶,但确实如此。至少在java7中。

You can convert the other way just as easily.

您可以同样轻松地转换另一种方式。

回答by Matt

Not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs? Why would this required a Double anyway?

不知道为什么你的地图中需要一个 Double 。就您要执行的操作而言,您有一个 int[] 并且您只想计算每个序列出现的次数?为什么这需要一个 Double 呢?

What I would do is to create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in it's version of these methods.

我要做的是使用适当的 .equals 和 .hashCode 方法为 int 数组创建一个包装器,以解决 int[] 对象本身不考虑这些方法版本中的数据这一事实。

public class IntArrayWrapper {
    private int values[];

    public IntArrayWrapper(int[] values) {
        super();
        this.values = values;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(values);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        IntArrayWrapper other = (IntArrayWrapper) obj;
        if (!Arrays.equals(values, other.values))
            return false;
        return true;
    }

}

And then use google guava's multiset, which is meant exactly for the purpose of counting occurances, as long as the element type you put in it has proper .equals and .hashCode methods.

然后使用 google guava 的 multiset,这正是为了计算出现次数的目的,只要您放入其中的元素类型具有适当的 .equals 和 .hashCode 方法。

List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
    multiset.add(new IntArrayWrapper(values));
}

Then, to get the count for any particular combination:

然后,要获取任何特定组合的计数:

int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));

回答by silver

Using regular for-loop without external libraries:

使用没有外部库的常规 for 循环:

Convert int[] to Integer[]:

将 int[] 转换为 Integer[]:

int[] primitiveArray = {1, 2, 3, 4, 5};
Integer[] objectArray = new Integer[primitiveArray.length];

for(int ctr = 0; ctr < primitiveArray.length; ctr++) {
    objectArray[ctr] = Integer.valueOf(primitiveArray[ctr]); // returns Integer value
}

Convert Integer[] to int[]:

将 Integer[] 转换为 int[]:

Integer[] objectArray = {1, 2, 3, 4, 5};
int[] primitiveArray = new int[objectArray.length];

for(int ctr = 0; ctr < objectArray.length; ctr++) {
    primitiveArray[ctr] = objectArray[ctr].intValue(); // returns int value
}

回答by Sheepy

Native Java 8 (one line)

原生 Java 8(一行)

With Java 8, int[]can be converted to Integer[]easily:

使用 Java 8,int[]可以Integer[]轻松转换为:

int[] data = {1,2,3,4,5,6,7,8,9,10};

// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );

// To boxed list
List<Integer> you  = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );

As others stated, Integer[]is usually not a good map key. But as far as conversion goes, we now have a relatively clean and native code.

正如其他人所说,Integer[]通常不是一个好的地图键。但就转换而言,我们现在有一个相对干净的原生代码。

回答by Harsh

  1. Convert int[] to Integer[]

    public static Integer[] toConvertInteger(int[] ids) {
    
      Integer[] newArray = new Integer[ids.length];
         for (int i = 0; i < ids.length; i++) {
           newArray[i] = Integer.valueOf(ids[i]);
         }
       return newArray;
    }
    
  2. Convert Integer[] to int[]

    public static int[] toint(Integer[] WrapperArray) {
    
       int[] newArray = new int[WrapperArray.length];
          for (int i = 0; i < WrapperArray.length; i++) {
             newArray[i] = WrapperArray[i].intValue();
          }
       return newArray;
    }
    
  1. 将 int[] 转换为 Integer[]

    public static Integer[] toConvertInteger(int[] ids) {
    
      Integer[] newArray = new Integer[ids.length];
         for (int i = 0; i < ids.length; i++) {
           newArray[i] = Integer.valueOf(ids[i]);
         }
       return newArray;
    }
    
  2. 将 Integer[] 转换为 int[]

    public static int[] toint(Integer[] WrapperArray) {
    
       int[] newArray = new int[WrapperArray.length];
          for (int i = 0; i < WrapperArray.length; i++) {
             newArray[i] = WrapperArray[i].intValue();
          }
       return newArray;
    }