侧边栏壁纸
  • 累计撰写 43 篇文章
  • 累计创建 0 个标签
  • 累计收到 35 条评论

目 录CONTENT

文章目录

Java 判断两个数组是否相等

import java.util.*;

class Untitled {
	public static void main(String[] args) {
		Set<int[]> s = new HashSet<>();
		s.add(new int[] {1, 2});
		s.add(new int[] {3, 4});
		s.add(new int[] {1, 2});
		
		System.out.println(s.size());		// 输出:3
	}
}

Java中基本类型比较相等是只比较 内容(值) 是否相等,对象类型则通过hashCodeequals方法比较两个对象是否相等。int[]等数组类型在Java中是对象类型,不是基本数据类型,Java提供给我们的对象类型我们不好重写hashCodeequals方法从而自定义比较方式。但是,我们可以通过Arrays.equals(arr1, arr2)方法比较两个数组中存储的值是否相等。比如:

    int[] a = new int[] { 0, 0 };
    HashSet<int[]> set = new HashSet<>();
    set.add(a);

    int[] b = new int[] { 0, 0 };
    
    boolean contains = set.stream().anyMatch(c -> Arrays.equals(c, b));
    
    System.out.println("Contains? " + contains);	// 输出:true

从而重写开头的程序:

import java.util.*;

class Untitled {
	public static void main(String[] args) {
		Set<int[]> s = new HashSet<>();
		
		int[] t1 = new int[] {1, 2};
		if (!hasContains(s, t1)) s.add(t1);
		
		int[] t2 = new int[] {3, 4};
		if (!hasContains(s, t2)) s.add(t2);
		
		int[] t3 = new int[] {1, 2};
		if (!hasContains(s, t3)) s.add(t3);
		
		System.out.println(s.size());	// 输出:2
	}
	
	private static boolean hasContains(Set<int[]> s, int[] t) {
		boolean contains = s.stream().anyMatch(e -> Arrays.equals(e, t));
		return contains;
	}
}

更有效率的写法是(推荐)使用List代替int[]数组:

import java.util.*;

class Untitled {
	public static void main(String[] args) {
		Set<ArrayList<Integer>> s = new HashSet<>();
		s.add(List.of(1, 2));
		s.add(List.of(3, 4));
		s.add(List.of(1, 2));
		
		System.out.println(s.size());	// 输出:2
	}
}

Preference

0

评论区