简体   繁体   English

如何从Java中的二维数组中删除元素

[英]How to remove an element from the two dimensional array in java

I have a multi dimensional array as 我有一个多维数组

private int numbers[][] ={{ 170, 100 },{ 270, 100 },{ 370, 100 },{ 470, 100 }}

Now i am changing there positions using Collections.shuffle(Arrays.asList(numbers)); 现在我正在使用Collections.shuffle(Arrays.asList(numbers));更改位置Collections.shuffle(Arrays.asList(numbers)); Now i want to remove the the first item from the shuffled array ie if the first item is {170,100} , it must be deleted from the array. 现在,我想从改组后的数组中删除第一项,即如果第一项是{170,100} ,则必须从数组中删除它。 For that, i tried to do something like this 为此,我试图做这样的事情

 List<int[]> points =Arrays.asList(numbers);
 Collections.shuffle(points);
 points.remove(0);

but it is throwing java.lang.UnsupportedOperationException could anybody help me out to remove the first element from the two dimensional day. 但是它抛出了java.lang.UnsupportedOperationException ,有人可以帮我从二维日中删除第一个元素。

Use following code: 使用以下代码:

 List<int[]> points =new ArrayList(Arrays.asList(numbers));
 Collections.shuffle(points);
 points.remove(0);

怎么样

List<int[]> points = new ArrayList(Arrays.asList(numbers));

Well, its written in the API of Arrays#asList method 好吧,它是用Arrays#asList方法的API编写的

Returns a fixed-size list backed by the specified array. 返回由指定数组支持的固定大小的列表。 (Changes to the returned list "write through" to the array.) (更改为将返回列表“直写”到数组。)

You cannot modify the returned list. 您无法修改返回的列表。 What you can do is to employ Masud's suggestion . 您可以做的就是采用Masud的建议

The problem is that Arrays.asList returns a List which is privately declared in Arrays class. 问题是Arrays.asList返回一个在Arrays类中私下声明的List。

 private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable

and doesn't implement modification operations, thus yuo're getting 并且不执行修改操作,因此

public E remove(int index) {
    throw new UnsupportedOperationException();
}

from it's superclass AbstractList. 从它的超类AbstractList。

As Reimeus suggested: wrap it into java.util.ArrayList or LinkedList 如Reimeus所建议:将其包装到java.util.ArrayList或LinkedList中

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

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