public class Album implements Comparable<Album> {
private final String title;
private final String artist;
private final int year;
private double price;
private int unitsSold;
/**
* Construct a Album object with the given title, artist, year, price, and unitsSold.
* @param title
* @param artist
* @param year
* @param price
* @param unitsSold
*
* @throws IllegalArgumentException if title or artist is null, year, price, or unitsSold is negative.
*/
public Album(String title, String artist, int year, double price, int unitsSold) {
if (title == null || artist == null || year < 0 || price < 0 || unitsSold < 0) {
throw new IllegalArgumentException("Invalid input");
}
this.title = title;
this.artist = artist;
this.year = year;
this.price = price;
this.unitsSold = unitsSold;
}
/**
* Compares two Album objects based on their titles in ascending order.
*/
@Override
public int compareTo(Album o) {
int titleComp = this.title.compareTo(o.title);
return titleComp;
}
public String getTitle() {
return this.title;
}
public String getArtist() {
return this.artist;
}
public int getYear() {
return this.year;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
if (price < 0) {
throw new IllegalArgumentException("Invalid input");
}
this.price = price;
}
public int getUnitsSold() {
return this.unitsSold;
}
public void increaseUnitsSold(int unitsSold) {
if (unitsSold < 0) {
throw new IllegalArgumentException("Invalid input");
}
this.unitsSold += unitsSold;
}
}
This compareTo
method compares this
Album object with the specified Album object, to determine the order of the two objects. In this case, the order is determined by the titles of the albums in ascending order.
We return a negative number if this
Album object should come "before" the specified Album object, a positive number if this
Album object should come "after" the specified Album object, and 0 if this
Album object is "equal to" the specified Album object.
This compareTo
method compares this
Album object with the specified Album object, to determine the order of the two objects. In this case, the order is determined by the titles of the albums in ascending order.
We return a negative number if this
Album object should come "before" the specified Album object, a positive number if this
Album object should come "after" the specified Album object, and 0 if this
Album object is "equal to" the specified Album object.
Here we declare the Album
as being Comparable
to other Album
objects.
The Comparable
interface is used when we want to define a "natural" ordering
for a class.
Implementing this interface forces us to implement the compareTo
method.
Here we declare the Album
as being Comparable
to other Album
objects.
The Comparable
interface is used when we want to define a "natural" ordering
for a class.
Implementing this interface forces us to implement the compareTo
method.
String
object is compared lexicographically to the
character sequence represented by the argument string. The result is
a negative integer if this String
object
lexicographically precedes the argument string. The result is a
positive integer if this String
object lexicographically
follows the argument string. The result is zero if the strings
are equal; compareTo
returns 0
exactly when
the equals(Object)
method would return true
.
String
object is compared lexicographically to the
character sequence represented by the argument string. The result is
a negative integer if this String
object
lexicographically precedes the argument string. The result is a
positive integer if this String
object lexicographically
follows the argument string. The result is zero if the strings
are equal; compareTo
returns 0
exactly when
the equals(Object)
method would return true
.
This is the definition of lexicographic ordering. If two strings are
different, then either they have different characters at some index
that is a valid index for both strings, or their lengths are different,
or both. If they have different characters at one or more index
positions, let k be the smallest such index; then the string
whose character at position k has the smaller value, as
determined by using the <
operator, lexicographically precedes the
other string. In this case, compareTo
returns the
difference of the two character values at position k
in
the two string -- that is, the value:
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case,this.charAt(k)-anotherString.charAt(k)
compareTo
returns the difference of the lengths of the
strings -- that is, the value:
this.length()-anotherString.length()
For finer-grained String comparison, refer to
Collator
.
compareTo
in interface Comparable<String>
anotherString
- the String
to be compared.0
if the argument string is equal to
this string; a value less than 0
if this string
is lexicographically less than the string argument; and a
value greater than 0
if this string is
lexicographically greater than the string argument.String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
String
class represents character strings. All
string literals in Java programs, such as "abc"
, are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2, 3); String d = cde.substring(1, 2);
The class String
includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character
class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null
argument to a constructor
or method in this class will cause a NullPointerException
to be
thrown.
A String
represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character
class for
more information).
Index values refer to char
code units, so a supplementary
character uses two positions in a String
.
The String
class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char
values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator
class provides methods for
finer-grain, locale-sensitive String comparison.
javac
compiler
may implement the operator with StringBuffer
, StringBuilder
,
or java.lang.invoke.StringConcatFactory
depending on the JDK version. The
implementation of string conversion is typically through the method toString
,
defined by Object
and inherited by all classes in Java.This part ensures that our compareTo
method takes in an Album
object as a parameter, and not any other type.
compareTo
method is referred to as
its natural comparison method.This part ensures that our compareTo
method takes in an Album
object as a parameter, and not any other type.
compareTo
method is referred to as
its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted
automatically by Collections.sort
(and
Arrays.sort
). Objects that implement this
interface can be used as keys in a sorted map or as
elements in a sorted set, without the need to
specify a comparator.
The natural ordering for a class C
is said to be consistent
with equals if and only if e1.compareTo(e2) == 0
has
the same boolean value as e1.equals(e2)
for every
e1
and e2
of class C
. Note that null
is not an instance of any class, and e.compareTo(null)
should
throw a NullPointerException
even though e.equals(null)
returns false
.
It is strongly recommended (though not required) that natural orderings be
consistent with equals. This is so because sorted sets (and sorted maps)
without explicit comparators behave "strangely" when they are used with
elements (or keys) whose natural ordering is inconsistent with equals. In
particular, such a sorted set (or sorted map) violates the general contract
for set (or map), which is defined in terms of the equals
method.
For example, if one adds two keys a
and b
such that
(!a.equals(b) && a.compareTo(b) == 0)
to a sorted
set that does not use an explicit comparator, the second add
operation returns false (and the size of the sorted set does not increase)
because a
and b
are equivalent from the sorted set's
perspective.
Virtually all Java core classes that implement Comparable
have natural orderings that are consistent with equals. One
exception is BigDecimal
, whose natural ordering equates
BigDecimal
objects with equal numerical values and different
representations (such as 4.0 and 4.00). For BigDecimal.equals()
to return true,
the representation and numerical value of the two
BigDecimal
objects must be the same.
For the mathematically inclined, the relation that defines the natural ordering on a given class C is:
{(x, y) such that x.compareTo(y) <= 0}.
The quotient for this total order is:
{(x, y) such that x.compareTo(y) == 0}.
It follows immediately from the contract for compareTo
that the
quotient is an equivalence relation on C
, and that the
natural ordering is a total order on C
. When we say that a
class's natural ordering is consistent with equals, we mean that the
quotient for the natural ordering is the equivalence relation defined by
the class's equals(Object)
method:{(x, y) such that x.equals(y)}.
In other words, when a class's natural ordering is consistent with
equals, the equivalence classes defined by the equivalence relation
of the equals
method and the equivalence classes defined by
the quotient of the compareTo
method are the same.
This interface is a member of the Java Collections Framework.
IllegalArgumentException
with the
specified detail message.IllegalArgumentException
with the
specified detail message.s
- the detail message.IllegalArgumentException
with the
specified detail message.IllegalArgumentException
with the
specified detail message.s
- the detail message.IllegalArgumentException
with the
specified detail message.IllegalArgumentException
with the
specified detail message.s
- the detail message.