forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquality.java
More file actions
100 lines (83 loc) · 2.48 KB
/
Copy pathEquality.java
File metadata and controls
100 lines (83 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.Arrays;
// David Anderson
public class Equality{
public static void main(String[] args){
// testing == with objects
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = {1, 2, 3, 4};
System.out.println(a == b); // incorrect
System.out.println(a);
System.out.println(b);
System.out.println(Arrays.equals(a, b)); // correct
System.out.println(equals(a, b));
System.out.println(equals(a, c));
System.out.println(contains(a, 1));
System.out.println(contains(a, 4));
}
public static boolean equals(int[] a, int[] b){
// If a == b, the arrays are equal.
if (a == b) return true;
// At this point, if a or b is null, the arrays aren't equal.
if (a == null || b == null) return false;
if(a.length != b.length){
return false;
}
// check all array elements for equality
for(int i = 0; i < a.length; i++){
if(a[i] != b[i]){
// found 2 elements in a and b that do not match. The arrays are not equal!
return false;
}
}
// all characters match. the arrays are equal!
return true;
}
public static boolean equals(double[] a, double[] b){
// If a == b, the arrays are equal.
if (a == b) return true;
// At this point, if a or b is null, the arrays aren't equal.
if (a == null || b == null) return false;
if(a.length != b.length){
return false;
}
// check all array elements for equality
for(int i = 0; i < a.length; i++){
if(a[i] != b[i]){
// found 2 elements in a and b that do not match. The arrays are not equal!
return false;
}
}
// all characters match. the arrays are equal!
return true;
}
public static boolean equals(boolean[] a, boolean[] b){
// If a == b, the arrays are equal.
if (a == b) return true;
// At this point, if a or b is null, the arrays aren't equal.
if (a == null || b == null) return false;
if(a.length != b.length){
return false;
}
// check all array elements for equality
for(int i = 0; i < a.length; i++){
if(a[i] != b[i]){
// found 2 elements in a and b that do not match. The arrays are not equal!
return false;
}
}
// all characters match. the arrays are equal!
return true;
}
public static boolean contains(int[] a, int n){
if(a == null){
return false;
}
for(int i = 0; i < a.length; i++){
if(a[i] == n){
return true;
}
}
return false;
}
}