代码之家  ›  专栏  ›  技术社区  ›  unknown

如何在Java中使用数组列表?

  •  0
  • unknown  · 技术社区  · 17 年前

    List<int[]> 或 Map<int[],Boolean> 但是这非常困难,因为Java中的数组没有实现 equals() 方法如果两个数组 a 和 b a.equals(b) 返回false。

    虽然 java.util.Arrays.equals() 比较数组是否相等,如何获得 List ?

    int[] 是描述坐标的数组[x,y,z]。我想把这些坐标放到一个坐标系中 列表 Map

    4 回复  |  直到 17 年前
        1
  •  9
  •   Richard Nichols    17 年前

    为什么不声明你自己的类呢?例如

    class Point3D {
      int x, y, z;
    
      public boolean equals() {
        // logic
      }
    }
    

    然后声明列表<Point3D>。

        2
  •  3
  •   Tom Hawtin - tackline    17 年前

    equals (及 hashCode 也许 compare 可能地 toString

    public final class IntArrayWrapper {
        private final IntArrayWrapper[] values;
        public IntArrayWrapper(int... values) {
            if (values == null) {
                throw new NullPointerException();
            }
            this.values = values;
        }
        @Override public boolean equals(Object obj) {
            if (!(obj instanceof IntArrayWrapper)) {
                return false;
            }
            IntArrayWrapper other = (IntArrayWrapper)obj;
            return java.util.Arrays.equals(this.values, other.values);
        }
        @Override public int hashCode() {
            return java.util.Arrays.hashCode(values);
        }
        public int[] getValues() {
            return values;
        }
        [...]
    }
    

    在这种特定情况下,使用数组包含某些固定数据值是一种糟糕的设计。正确操作:

    public final class Point {
        private final int x;
        private final int y;
        private final int z;
    
        public static Point of(int x, int y, int z) {
            return new Point(x, y, z);
        }
        private Point(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
        @Override public boolean equals(Object obj) {
            if (!(obj instanceof Point)) {
                return false;
            }
            Point other = (Point)obj;
            return
                this.x == other.x &&
                this.y == other.y &&
                this.z == other.z;
        }
        @Override public int hashCode() {
            int hash;
            hash = x;
            hash = hash*41+y;
            hash = hash*41+z;
            return hash;
        }
        [...]
    }
    
        3
  •  2
  •   duffymo    17 年前

    首先,这不是合法的语法。列表只能采用单个泛型类型。

    第二,我想说的是,如果你担心在这么低的水平上做事,你就没有足够的抽象思维。数组数组或列表列表非常常见。为线性代数创建矩阵类的人一直在使用它们。但是,当您对类的客户机隐藏这些实现细节时,您最好利用对象和Java。试试你的情况,看看是否有帮助。

        4
  •  0
  •   Carl    17 年前