Originally Posted by
lorenxvii
public class Person {
String name;
String age;
public Person (String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
First, your Person class is "quite" correct. The main problem is that age instance variable is String but getAge returns an int. This gives you a compilation error!
Second (less important) declare instances variables as
private .
Originally Posted by
lorenxvii
What exactly is happening behind the scenes? I don't understand mostly the part where it returns a 0, a 1, or a -1. After it returns one of those values, what really happens next?
For the generics, why do we use Person?
Just one little note before continue with your questions: it's not very good that you define a comparator implementation
into the class of your objects.
And technically there's also a problem: your SomeComparator is an "inner" class. To instantiate an inner class you must have an instance of the "container" (Person) class. And
new Person.SomeComparator() is not correct!
Please, define the comparator class outside Person (really better in another source code!)
The Comparator is "generic" just for the type safety in
your source code. Who uses the comparator instance (the code into the sort() ) doesn't care about your parametrization. ArrayList simply know to contain Object items. And the sort() simply expects to pass that Objects to parameter 1 and 2 of the compare.
You can even use Comparator without generics, as in the "old" way (but you have to do some casts).
Your comparator must only respond about the comparation between 2 Person objects. It's the sort() implementation that makes lots (how many are needed, depending on the sort algorithm) of comparations 2 items per time to deduce and apply the entire order.
Originally Posted by
lorenxvii
For the displaying of the list, is the method toString() being accessed to output the list in the System.out.println statement?
Yes. The toString() of ArraysList returns a String that appropriately describes the content of the list.