import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //"2 10000000 10000000" comes in
int n = sc.nextInt();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) list.add(sc.nextInt());
for (int i = 0; i < n-1; i++) {
if (list.get(i) == list.get(i+1)) {
System.out.println("equal");
return;
}
}
System.out.println("Not equal");
}
}
list.get (i)
should be 10000000, and list.get (i + 1)
should be the same 10000000, but the result is "not equal". why? ??
==
, object type is ʻequals`Since Integer is an object type, when comparing with ==
, it seems that it will be "not equal" because it will check whether it is the same instance.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //"2 10000000 10000000" comes in
int n = sc.nextInt();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) list.add(sc.nextInt());
for (int i = 0; i < n-1; i++) {
if (list.get(i).equals(list.get(i+1))) {
System.out.println("equal");
return;
}
}
System.out.println("Not equal");
}
}
//result
//equal
In conclusion, when comparing numbers, I had to be careful to use ==
for primitive types and ʻequals` for object types.
Recommended Posts