В Java, когда оператор «==» используется для сравнения двух объектов, он проверяет, ссылаются ли объекты на одно и то же место в памяти. Другими словами, он проверяет, являются ли имена двух объектов в основном ссылками на одно и то же место в памяти.
Класс Java String фактически переопределяет реализацию equals () по умолчанию в классе Object и переопределяет этот метод, чтобы он проверял только значения строк, а не их местоположения в памяти. Это означает, что если вы вызываете метод equals () для сравнения двух объектов String, то, пока действительная последовательность символов равна, оба объекта считаются равными.
Оператор
==
проверяет, являются ли две строки точно одним и тем же объектом.Метод
blockquote>.equals()
проверяет, имеют ли две строки одно и то же значение.
If you only want to create comparison functions then you could use the default comparer for the type T
. For example:
public static T Max<T>(T x, T y)
{
return (Comparer<T>.Default.Compare(x, y) > 0) ? x : y;
}
If T
implements IComparable
then that comparer will be used; if T
doesn't implement IComparable
but does implement IComparable
then that comparer will be used; if T
doesn't implement either IComparable
or IComparable
then a runtime exception will be thrown.
If you want/need to do more than just compare the items then you could have a look at the generic operators implementation in MiscUtil and the related article.
From memory, T also needs to be IComparable
(add that to the where
), and then you use v1.CompareTo(v2) > 0
etc.
You probably want to constrain the generic types to implement IComparable
:
public T Max<T>(T v1, T v2) where T: struct, IComparable<T>
and then use the CompareTo
method:
{
return (v1.CompareTo(v2) > 0 ? v1 : v2);
}