Home > Programming > How to avoid getting -Xlint errors during compilation when using Collections.sort() and/or Arrays.sort()

How to avoid getting -Xlint errors during compilation when using Collections.sort() and/or Arrays.sort()

-Xlint errors tell us that we have not safeguarded our
types i.e. we do not have type-safety

Here is how you can avoid -Xlint errors at the same time
have either a Collection ( e.g. Set, ArrayList, List,
HashMap etc. ) or an Array of objects that you need to sort

------------------------------------------------------

Imagine we have a class called Person in which our fields are
name(String) and age(int), and we want to either have a
Collection or an Array of Person objects which requires to be
sorted in order of age at some point of execution.
Here is how we do it.

class Person implements Comparable< Person >
{
	String name;
	int age;

	public int compareTo( Person p )
	{
		return age - p.age; // sorting by age
	}
}

If you have a Collection called collectionOfPerson and an
Array called arrayOfPerson then here is how you can sort them
in order of their ages.

Collections.sort( collectionOfPerson );
Arrays.sort( arrayOfPerson );
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: