You can't directly compare an int[] to an int. You need to access a value in the array and then compare.
int[] myArray = {1, 2, 3};
int value = 1;
if (myArray[0] == value) {/*do something*/}
Answer from Grice on Stack OverflowYou can't directly compare an int[] to an int. You need to access a value in the array and then compare.
int[] myArray = {1, 2, 3};
int value = 1;
if (myArray[0] == value) {/*do something*/}
You cannot compare an array with a variable that holds just one data.
You know, array is a data structure.
You must loop through the array and then compare each value of the array with t.
for(int i = 0; i < h.length; i++) {
if( t == h[i] ) // Or any other comparison operator
/* Perform some action.*/;
}
First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.
A better approach would be to compare each element i to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 21 -> 31 -> 41 -> 52 -> 32 -> 42 -> 53 -> 43 -> 54 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
If it's really an array, you want:
if (list[0] == list[2] && list[1] == list[3])
Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:
if (list[0].equals(list[2])) && list[1].equals(list[3]))
Although that will then go bang if any of the values is null. You might want a helper method to cope with this:
public static objectsEqual(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then:
if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
If you've really got an ArrayList instead of an array then all of the above still holds, just using list.get(x) instead of list[x] in each place.
if(list[0] == list[2] && list[1] == list[3]){
System.out.println("equal");
}
If they are strings:
if(list[0].equals(list[2]) && list[1].equals(list[3])){
System.out.println("equal");
}