/**
*
*/
package de.tutorials;
import java.util.Collections;
import java.util.Vector;
/**
* @author Tom
*/
public class CollectionSortExample {
/**
* @param args
*/
public static void main(String[] args) {
Vector<Person> persons = new Vector<Person>();
persons.add(new Person("Stefan", 12));
persons.add(new Person("Dietmar", 12));
persons.add(new Person("Jürgen", 20));
persons.add(new Person("Thomas", 23));
persons.add(new Person("Thomas", 2));
Collections.sort(persons);
System.out.println(persons);
}
static class Person implements Comparable<Person> {
String name;
int age;
/**
* @param name
* @param age
*/
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Person other = (Person) obj;
if (age != other.age) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
public int compareTo(Person o) {
//First order by name
int result = name.compareTo(o.name);
if (0 == result) {
//if names are equal order by age, youngest first
result = age - o.age;
}
return result;
}
@Override
public String toString() {
return this.name + ": " + this.age;
}
}
}