如何在Java中制作一组数组?

编程入门 行业动态 更新时间:2024-10-16 18:27:33
本文介绍了如何在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 类已经包装了一个数组,您可以扩展它并覆盖equals 和 hashCode方法.这是一个示例:

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中制作一组数组?

本文发布于:2023-05-23 15:04:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!