JAVA比较两个数组中的元素是否相同

分手后的思念是犯贱 2023-09-30 09:38 86阅读 0赞

做考试答案判断时,考试多选题正确答案可能是多个如{“a”, “b”, “c”},但可能出现不同的选择顺序,所以要对其进行判断
代码实现如下

  1. /**
  2. * 性能差,因为要排序两次
  3. */
  4. @Test
  5. public void test1() {
  6. String[] rightAnswer = {
  7. "a", "b", "c"};
  8. // bac cba ...不管什么顺序结果都一样
  9. String[] reply = {
  10. "a", "c", "b"};
  11. Arrays.sort(rightAnswer);
  12. Arrays.sort(reply);
  13. //结果为 两个数组中的元素值相同
  14. if (Arrays.equals(rightAnswer, reply)) {
  15. System.out.println("两个数组中的元素值相同");
  16. } else {
  17. System.out.println("两个数组中的元素值不相同");
  18. }
  19. }
  20. /**
  21. * 性能高,只用遍历一遍
  22. */
  23. @Test
  24. public void test2() {
  25. String[] s1 = {
  26. "a", "b", "c"};
  27. // bac cba ...不管什么顺序结果都一样
  28. String[] s2 = {
  29. "a", "c", "b"};
  30. List<String> rightAnswer = Arrays.asList(s1);
  31. List<String> reply1 = Arrays.asList(s2);
  32. Boolean judge = true;
  33. for (String s : reply1) {
  34. if (!rightAnswer.contains(s)) {
  35. judge = false;
  36. break;
  37. }
  38. }
  39. //结果为 两个数组中的元素值相同
  40. if (judge) {
  41. System.out.println("两个数组中的元素值相同");
  42. } else {
  43. System.out.println("两个数组中的元素值不相同");
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读