如何在Java中制作一组数组? [英] How to make a set of arrays in Java?

查看:60
本文介绍了如何在Java中制作一组数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于数组中的 equals 函数只检查实例,所以它不适用于 Set.因此,我想知道如何在 Java 中创建一组数组?

Since the equals function in array only check the instance, it doesn't work well with Set. Hence, I wonder how to make a set of arrays in Java?

一种可能的方法是将每个数组放在一个对象中,并为该类实现 equals 函数,但这会降低性能吗?

One possible way could be put each array in an object, and implement equals function for that class, but will that decrease the performance too much?

推荐答案

由于 ArrayList 类已经包装了一个数组,您可以扩展它并覆盖equalshashCode方法.这是一个示例:

Since the ArrayList class already wraps an array, you can extend it and override the equals and hashCode methods. Here is a sample:

public MyArrayList extends ArrayList<MyClass> {

    @Override
    public boolean equals(Object o) {
        if (o instanceof MyArrayList) {
            //place your comparison logic here
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        //just a sample, you can place your own code
        return super.hashCode();
    }
}

更新:

您甚至可以覆盖它用于一般用途,只需将代码更改为:

You can even override it for a generic use, just changing the code to:

public MyArrayList<T> extends ArrayList<T> {
    //overrides the methods you need
    @Override
    public boolean equals(Object o) {
        if (o instanceof MyArrayList) {
            //place your comparison logic here
            return true;
        }
        return false;
    }
}

这篇关于如何在Java中制作一组数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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