Как работает Integer.compare?
Программа кошачья битва.
Суть в том, что создаём объекты класса Cat, задаём аргументы и на основе этих аргументов сравниваем, кто победит. Всё понятно, кроме того, как работает Integer.compare.
Все аргументы двух котов, которые мы сравниваем, сохраняем в одну переменную int score, и я не могу понять, как по данным из одной переменной мы узнаем, что, допустим, cat2 слабее cat1?
public boolean fight(Cat anotherCat) {
int ageScore = Integer.compare(this.age, anotherCat.age);
int weightScore = Integer.compare(this.weight, anotherCat.weight);
int strengthScore = Integer.compare(this.strength, anotherCat.strength);
int score = ageScore + weightScore + strengthScore;
return score > 0; // return score > 0 ? true : false;
}
Я понимаю если бы мы сравнивали аргументы cat1 и cat2 и вносили в две разные переменные, допустим:
public boolean fight(Cat anotherCat) {
int i = 0, j = 0;
if (this.weight > anotherCat.weight) i++;
else if (this.weight != anotherCat.weight) j++;
if (this.age > anotherCat.age) i++;
else if (this.age != anotherCat.age) j++;
if (this.strength > anotherCat.strength) i++;
else if (this.strength != anotherCat.strength) j++;
}
Весь код программы:
public class Solution {
public static void main(String[] args) {
Cat cat1 = new Cat("Dana Wait", 5, 2, 2);
Cat cat2 = new Cat("Habib", 4, 3, 4);
Cat cat3 = new Cat("Mac Gregor", 6, 5, 3);
System.out.println(cat1.fight(cat2));
System.out.println(cat2.fight(cat3));
System.out.println(cat1.fight(cat3));
}
public static class Cat {
protected String name;
protected int age;
protected int weight;
protected int strength;
public Cat(String name, int age, int weight, int strength) {
this.name = name;
this.age = age;
this.weight = weight;
this.strength = strength;
}
public boolean fight(Cat anotherCat) {
int ageScore = Integer.compare(this.age, anotherCat.age);
int weightScore = Integer.compare(this.weight, anotherCat.weight);
int strengthScore = Integer.compare(this.strength, anotherCat.strength);
int score = ageScore + weightScore + strengthScore;
return score > 0; // return score > 0 ? true : false;
}
}
}
Ответы (3 шт):
Давайте постараюсь объяснить.
int ageScore = Integer.compare(this.age, anotherCat.age);
Что тут сравнивается и каков результат? Сравниваются значения age у двух котов. Если первый больше, то результат равен 1, если равен, то 0 и если меньше, то -1.
Отсюда следует, что ageScore может быть -1, либо 0, либо 1.
Итак по 3 параметрам котов.
Итоговый счёт ведётся по сумме трёх раундов по параметрам.
И если сумма score > 0 то кот (this) сильнее.
Тут сравнение реализовано таким образом, что переменная score меньше нуля, если кот представленный this слабее, равна нулю, если сила такая же и больше нуля, если сильнее.
То есть в альтернативной реализации вы бы сравнивали i и j, а тут нужно сравнивать score с нулем, имеем соответствие:
i ? j | score ? 0
=======+============
i > j | score > 0
i == j | score == 0
i < j | score < 0
У вас каждое сравнение дает плюс 1 тому кто сильнее, и это точно то, что возвращает Integer.compare. Кто сильнее - тому 1, если равны - 0.
Как работает Integer.compare?
Открываем класс Integer и смотрим метод compare:
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Для наглядности этот код можно переписать так:
public static int compare(int x, int y) {
if (x < y) {
return -1;
} else if (x == y) {
return 0;
} else {
return 1;
}
}
т. е. метод compare сравнивает два числа между собой и возвращает:
-1- первое число меньше второго0- числа равны1- первое число больше второго