如何构建从二维int数组ArrayList的? [英] How to construct ArrayList from 2D int array?

查看:185
本文介绍了如何构建从二维int数组ArrayList的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维int数组,我想删除重复的行例如:

I have a 2D int array, i want to remove duplicate rows for example

30,40,50

50,30,40

30,40,50

在上面的例子中第2和放大器;第三行是重复第一排的。

in above example 2nd & 3rd row is duplicate of 1st row.

我知道的ArrayList 可以动态增加和水槽这是这个概念有用的,但我们如何转换 INT [] [] 的ArrayList

I know ArrayList can dynamically grow and sink which is useful class for this concept but how we convert int[][] into ArrayList.

推荐答案

首先,你应该创建一个类来保存你的数据其覆盖公共布尔等于(obj对象)公众诠释哈希code()来表示数据的平等。

First, you should create a Class to hold you data which override public boolean equals(Object obj) and public int hashCode() to indicate equality of the data.

public class Row {

    private int[] ints;

    public Row(int[] ints) {
        this.ints = ints.clone();
        Arrays.sort(this.ints);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(ints);
    }

    @Override
    public boolean equals(Object obj) {

        if(obj instanceof Row) {
            Row another = (Row) obj;
            int[] original = Arrays.copyOf(another.ints, another.ints.length);
            return Arrays.equals(ints, original);
        } else {
            return false;
        }
    }

    @Override
    public String toString() {
        return Arrays.toString(ints);
    }

}

测试用例

public class Test {

    public static void main(String[] args) {
        int[][] arrays = new int[][]{{30,40,50}, {50,30,40}, {30,40,50}, {10, 20, 30}};
        Set<Row> rows = new HashSet<Row>();
        for(int[] a: arrays) {
            rows.add(new Row(a));
        }
        for(Row row: rows) {
            System.out.println(row);
        }
    }
}

输出

[10, 20, 30]
[30, 40, 50]

这篇关于如何构建从二维int数组ArrayList的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆