So I am able to print the Gregorian Calendar for the current month, but when I am trying to flip to the next or previous month, it just seems to reprint the current month again. Please note that by "printing" the calendar, I mean that I am actually formatting it to look like I full calendar (all the days like a Google calendar, etc). Also, this program is in very early stages. Ultimately, I want it to support adding events to days, printing the events, etc.
Anyway, here is some code that I have that might be relevant:
MyCalendar class:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
public class MyCalendar {
GregorianCalendar calendar;
String[] months;
String[] dayOfWeek;
int todayDay;
int maxDays;
static PrintMenu print = new PrintMenu();
private HashMap<MyCalendar, Event> myCalHash = new HashMap<MyCalendar, Event>();
MyCalendar(){
calendar = new GregorianCalendar(); //capture today
months = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
dayOfWeek = new String[]{"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"};
todayDay = calendar.get(Calendar.DAY_OF_MONTH);
maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
public Calendar getCalendar(){
return calendar;
}
public void setCalendar(GregorianCalendar cal){
calendar = cal;
}
public Date getFirstDayOfMonth(){
return calendar.getTime();
//return calendar.get((Calendar.DAY_OF_WEEK) - 1);
}
public int getDay(){
return calendar.get(Calendar.DAY_OF_MONTH);
}
public int getMaximumDays(){
return maxDays;
}
public int getTodayDay(){
return todayDay;
}
public int getMonth(){
return calendar.get(Calendar.MONTH);
}
public int getYear(){
return calendar.get(Calendar.YEAR);
}
public void setNext(){
calendar.add(Calendar.MONTH, 1);
}
public void setPrevious(){
calendar.add(Calendar.MONTH, -1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
print.printCalendar(false);
print.printMenu();
System.out.println("I think we're done here!");
}
}
PrintMenu Class:
public class PrintMenu {
MenuHandler menu = new MenuHandler();
MyCalendar myCalendar = new MyCalendar();
void printCalendar(boolean withEvents){
int count = 0; //for formatting
int day = myCalendar.getTodayDay();
System.out.println(myCalendar.months[myCalendar.getMonth()] + " " + myCalendar.getYear());
System.out.print(myCalendar.dayOfWeek[6] + " ");
for(int i = 0; i < myCalendar.dayOfWeek.length - 1; i++){
System.out.print(myCalendar.dayOfWeek[i] + " ");
}
// int daysInMonth = myCalendar.getMaximumDays(); // 28
for(int i = 1; i <= myCalendar.dayOfWeek.length; i++){
count++;
if(!myCalendar.dayOfWeek[i].equals(myCalendar.getFirstDayOfMonth().toString().substring(0, 2))){
System.out.print(" ");
}else{
count = 0;
break;
}
}
System.out.println();
for(int i = 1; i <= myCalendar.getMaximumDays(); i++){
if(!withEvents){
if(i == day){
System.out.print("[" + i + "]");
}
if(i < 10){
System.out.print(" " + i + " ");
}else{
if(i != day){
System.out.print(i + " ");
}
}
}
else{
if(i < 10){
System.out.print(" " + i + " ");
}else{
System.out.print(i + " ");
}
}
count++;
if(count >= 7){
System.out.println();
count = 0; //reset back
}
}
}
void printMenu(){
System.out.println("-------------------------------------------------------------------");
System.out.println("Select one of the following options: ");
System.out.println("[L]oad [V]iew by [C]reate, [G]o to [E]vent list [D]elete [Q]uit");
menu.handleChoice();
printMenu();
}
}
ViewCalendar class (this is where I'm trying to navigate the calendar and failing)
import java.util.Calendar;
import java.util.Scanner;
public class ViewCalendar {
Scanner sc = new Scanner(System.in);
MyCalendar myCalendar = new MyCalendar();
public void whatView(){
System.out.print("[D]ay view or [M]view? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'D'){ dayView(); }
else if(Character.toUpperCase(userChoice) == 'M'){ monthView(); }
else{
System.out.println("Invalid choice.");
whatView();
}
}
public void dayView(){
//print day calendar
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
}
else if(Character.toUpperCase(userChoice) == 'N'){
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}
public void monthView(){
//print month calendar
myCalendar.print.printCalendar(true);
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
myCalendar.setPrevious();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'N'){
myCalendar.setNext();
myCalendar.print.printCalendar(true);
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
dayView();
}
}
}
Anyway, I hope that's not too much information. I followed the calendar.add() syntax, but it doesn't seem to have any effect.
I appreciate any insight you guys may have!
Here is the MenuHandler class:
import java.util.Scanner;
public class MenuHandler {
Scanner sc = new Scanner(System.in);
ViewCalendar view = new ViewCalendar();
public void handleChoice(){
char userChoice = sc.next().charAt(0);
switch(Character.toUpperCase(userChoice)){
case 'L':
case 'V': view.whatView();
// menu.printMenu();
case 'C':
case 'G':
case 'E':
case 'D':
case 'Q': return;
}
}
}
#hotshotennis you can try to use the method set() instead of method add() to manipulate the date.
public class MyCalendar {
.....
.....
public void setNext(){
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
}
public void setPrevious(){
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
}
.....
.....
}
Related
For class, I have to write a program using arrays where someone can look up popular baby names during a certain time frame. (Ex: The most popular boy and girl name from 1890-1910 is ....)
I think the program is decent, but it runs really slow. I don't know if it is just because of my code, or having a simple program look through a large file; but is there a way to speed up the process?
import java.io.*;
import java.util.*;
import java.net.URL;
public class BabyNamesMainDriver {
// ===========================================================================================
private static void process(Scanner sc, String[] args) throws Exception {
// The two arrays
ArrayList<BabyNameClass> boys = new ArrayList<BabyNameClass>();
ArrayList<BabyNameClass> girls = new ArrayList<BabyNameClass>();
System.out.println("Enter a start year between 1880 and 2016:");// start year
int startYear = sc.nextInt();
if (startYear < 1880 || startYear > 2016)// Error check
System.out.println("ERROR: Invalid start year.\n");
else
System.out.println("Enter a end year. Must be less then 2016 but greater than the start year :");// End year
int endYear = sc.nextInt();
if (endYear < 1880 || endYear > 2016)// Error check
System.out.println("ERROR: Invalid end year. \n");
else
System.out.println("Enter the number of baby names to list. ");// Number of baby names
int numOfNames = sc.nextInt();
// if (topBabies <= 0);//Error Check
// System.out.println("ERROR: Invalid number of names. \n");
ReadBabyNames(startYear, endYear, boys, girls);// Reads file info
// Header for top girl names
System.out.print("\nTop " + numOfNames + " Girl names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(girls.get(i));
}
// Header for top boy names
System.out.print("\nTop " + numOfNames + " Boy names:\n");
for (int i = 0; i < numOfNames; i++) {
System.out.println(boys.get(i));
}
sc.nextLine();
}
// ===========================================================================================
private static void ReadBabyNames(int startYear, int endYear, ArrayList<BabyNameClass> boys,
ArrayList<BabyNameClass> girls) throws IOException, Exception {
System.out.println("Please stand by...");
for (int year = startYear; year <= endYear; year++) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(
new URL("https://cs.stcc.edu/~silvestri/babynames/yob" + year + ".txt").openStream());// file from
// URL
sc.useDelimiter("\\s*,\\s*|\\s+");
while (sc.hasNextLine()) {
String name = sc.next();
String sex = sc.next();
int number = sc.nextInt();
sc.nextLine();
BabyNameClass babies = new BabyNameClass(name, number);
Collections.sort(boys);
Collections.sort(girls);
// Getting number of lil' babies
if (sex.equalsIgnoreCase("F")) {
int index = 1;
index = girls.indexOf(babies);
if (index == -1)
girls.add(babies);
else
girls.get(index).addToAmount(number);
} else {
int index = 1;
index = boys.indexOf(babies);
if (index == -1)
boys.add(babies);
else
boys.get(index).addToAmount(number);
}
}
}
}
// ===========================================================================================
public static void main(String args[]) throws Exception {
final String TITLE = "Baby Name Ranking";
final String CONTINUE_PROMPT = "\nDo this again? [y/N] ";
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
// ===========================================================================================
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.equalsIgnoreCase("Y");
}
}
2nd class
public class BabyNameClass implements Comparable<BabyNameClass> {
// ==========================
private String name;
private int num;
// ===========================================================================================
public BabyNameClass(String name, int num) {
this.name = name;
this.num = num;
}
// ===========================================================================================
public String getName() {
return this.name;
}
// ===========================================================================================
public int getNum() {
return this.num;
}
// ===========================================================================================
public void addToAmount(int num) {
this.num += num;
}
// ===========================================================================================
public void setAmount(int num) {
this.num = num;
}
// ===========================================================================================
public boolean equals(Object lak) {
if (lak == null)
return false;
if (this == lak)
return true;
if (getClass() != lak.getClass())
return false;
BabyNameClass Gu = (BabyNameClass) lak;
if (name == null) {
if (Gu.name != null)
return false;
} else if (!name.equals(Gu.name))
return false;
return true;
}
// ===========================================================================================
public int compareTo(BabyNameClass arg0) {
if (this.num < arg0.num)
return 1;
if (this.num > arg0.num)
return -1;
if (this.name.compareTo(arg0.name) > 0)
return 1;
if (this.name.compareTo(arg0.name) < 0)
return -1;
else
return 0;
}
// ===========================================================================================
public String toString() {
return " " + this.num + " babies were named " + this.name;
}
}
You're sorting two arraylists every single time you read a new line from the txt file. Why? Sorting is very cpu-intensive. Especially when those txt files you are using are huge.
Just try and move the sort out of the while loop.
So I have an assignment to do the following two parameters (there were four in total but the first two were beyond easy)
Parameter 1: coinToss
This method simulates tossing a coin and prints out "Head" or "Tail"
For example, when this method is called, it will randomly print out either "Head" or "Tail"
Parameter 2: dayOfWeek
Given a number (1-7), this method returns the appropiate day of the week.
For example, Given 1 this method returns "Sunday".
I was actually able to do these two parameters my OWN method and worked perfectly fine. But he recently uploaded how he wanted us to do it and now need help!
How he wants us to do it:
Parameter 3:
m.coinToss();
Parameter 4:
System.out.print("Type any number (1-7): ");
int day = in.nextInt();
String dayOfWeek = m.dayOfWeek(day);
System.out.printf("%s is the %d day of the week.\n", dayOfWeek, day);
How I did it:
public void coinToss (int r) {
boolean headOrTail = (r % 2 == 0);
if (headOrTail) {
System.out.println("Heads");
} else {
System.out.println("Tails.");
}
}
public void dayOfWeek (int whichDay) {
Scanner in = new Scanner (System.in);
Homework2 m = new Homework2();
if (whichDay == 1) {
System.out.println("Sunday.");
}
if (whichDay == 2) {
System.out.println("Monday.");
}
if (whichDay == 3) {
System.out.println("Tuesday.");
}
if (whichDay == 4) {
System.out.println("Wednesday.");
}
if (whichDay == 5) {
System.out.println("Thursday.");
}
if (whichDay == 6) {
System.out.println("Friday.");
}
if (whichDay == 7) {
System.out.println("Saturday.");
}
if (whichDay > 7) {
int day;
System.out.print("Please enter a number from 1 and 7. ");
day = in.nextInt();
m.dayOfWeek(day);
}
}
public static void main(String[] args) {
int headOrTail = random.nextInt(100) + 1;
m.coinToss(headOrTail);
System.out.println();
System.out.print("Type any number (1-7): ");
int day = in.nextInt();
m.dayOfWeek(day);
}
Your implementation of coinToss is mostly fine, what you're missing is basically a way to generate a random number. In Java you have the java.util.Random class which does just that:
Random random = new Random();
int randomInteger = random.nextInt();
And now that you have your random integer, I'll leave you to plug that into your coin toss :)
Reference for Random: http://docs.oracle.com/javase/8/docs/api/java/util/Random.html
Edit: bonus points: since you only have two possible values, heads and tails, you can use the nextBoolean() method and simplify your coin toss condition. Good luck!
You can print both dayOfWeek and day.. So You try this one.
You need to change the return type of dayOfWeek method from void to String.
import java.util.Random;
import java.util.Scanner;
public class WeekDay {
static WeekDay m = new WeekDay();
static Scanner in = new Scanner (System.in);
static Random rand = new Random();
String day;
public void coinToss () {
int headOrTail = rand.nextInt(100) + 1;
boolean check = (headOrTail % 2 == 0);
if (check) {
System.out.println("Heads");
}else {
System.out.println("Tails.");
}
}
public String dayOfWeek (int whichDay) {
if (whichDay == 1) {
day = "Sunday.";
}
if (whichDay == 2){
day = "Monday.";
}
if (whichDay == 3){
day = "Tuesday.";
}
if (whichDay == 4){
day = "Wednesday.";
}
if (whichDay == 5){
day = "Thursday.";
}
if (whichDay == 6){
day = "Friday.";
}
if (whichDay == 7){
day = "Saturday.";
}
if (whichDay > 7) {
int dayCount;
System.out.print("Please enter a number from 1 and 7. ");
dayCount = in.nextInt();
m.dayOfWeek(dayCount);
}
return day;
}
public static void main(String[]args){
m.coinToss();
System.out.println("\n");
System.out.print("Type any number (1-7): ");
int dayCount = in.nextInt();
m.dayOfWeek(dayCount);
String dayOfWeek = m.dayOfWeek(dayCount);
System.out.printf("%s is the %d day of the week.\n", dayOfWeek, dayCount);
}
}
I need to write a Java program (class Date) and "class NextDay that calculates and prints the date of the next day by entering the day, month, and year."
At public Date getNextDay() method I must use return null, otherwise it gives error. How can I avoid return null?
Here are my codes;
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
public Date getNextDay(){
try {
if(day < getMaxDaysInMonth()){
return new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
return new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
return new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return null;
}
public int getDay(){
return day;
}
public int getMonth(){
return month;
}
public int getYear(){
return year;
}
public boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public String toString(){
return this.day + "." + this.month + "." + this.year;
}
}
public class NextDay {
public static void main(String args[]) throws Exception{
Date dateObj = new Date(28, 2, 2015);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}
Use a local variable and assign it and return at the end of the method and you can use jumping statements in your code if it can improve the performance
public Date getNextDay(){
Date date = new Date();
try {
if(day < getMaxDaysInMonth()){
date= new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
date = new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
date = new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return date;
}
I would suggest you return a date in the past and avoid returning null.
I suggest to throw an exception. As part of the exception you could also give some explanation about was was/is wrong.
Returning a specific date is not a good idea, because this Date could also match to a Date that was created in a valid way. I.e. the Date 01-01-1970 can be created without any problem, right? So it should not be returned as kind or marker for a problem.
Concerning your Date representation keep in mind that you can initialize a Date with Integer.MAX_VALUE for month, day, and year. What is the expected output in this case?
i am making a program that reads in the month 1-12 and the start day, 1-7 for sunday, monday, etc. it prints the first week fine but im having problems printing the rest of the days after the first week. it wont format the output to have a space between the rest of the days, only the first day after the first week.
side note: Keyboard is a class i have included in my project
heres my code:
import java.io.*;
public class CalendarMonth
{
static final int WEEK = 7;
public static void main(String[] args) throws IOException
{
String proceed;
char repeatCheck;
int days;
String leapYear;
char leapYearCheck;
int startDay;
do
{
days = getDays();
System.out.println(days);
System.out.println("Please enter a number 1-7 that the month starts on: (1 for sunday, 2 for monday, etc)");
startDay = Keyboard.readInt();
while(startDay < 1 || startDay > 7)
{
System.out.println("You did not enter a number 1-7, Try again: ");
startDay = Keyboard.readInt();
}
System.out.println(" s m t w th f sa");
printMonth(days,startDay);
System.out.println("\nWould you like to print another month?");
proceed = Keyboard.readString();
repeatCheck = proceed.charAt(0);
}while(repeatCheck == 'y');
}
public static int getDays() throws IOException
{
int month;
String leapYear;
int startDay;
int days = 0;
char leapYearCheck;
System.out.println("Please input a number 1-12 to print the corresponding month: ");
month = Keyboard.readInt();
while (month < 1 || month > 12)
{
System.out.println("You did not put a number 1-12, Try again: ");
month = Keyboard.readInt();
}
switch(month)
{
case 1: days = 31;
break;
case 2:
System.out.println("is it a leap year? ");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
while(leapYearCheck != 'y' && leapYearCheck != 'n')
{
System.out.println("you did not enter a yes or no answer, is it a leap year?");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
}
if (leapYearCheck == 'y')
{
days= 29;
}
else
{
days = 28;
}
break;
case 3: days = 31;
break;
case 4: days = 30;
break;
case 5: days = 31;
break;
case 6: days = 30;
break;
case 7: days = 31;
break;
case 8: days = 31;
break;
case 9: days = 30;
break;
case 10: days = 31;
break;
case 11: days = 30;
break;
case 12: days = 31;
break;
}
return days;
}
public static void printMonth(int days, int startDay)
{
int count;
count = startDay;
for (int counter = 1; counter <= 7; counter++)
{
if (counter < startDay)
{
System.out.print(" ");
count = count-1;
}
else
{
System.out.printf("%2d", count);
count++;
}
}
//int restOfTheMonth = (WEEK - startDay);
System.out.println();
for(int restOfTheMonth = count; restOfTheMonth <= days; restOfTheMonth++)
{
if (restOfTheMonth%WEEK==0)
{
System.out.println();
}
System.out.printf("%2d", restOfTheMonth);
}
}
}
As of now my highscore list is only sorted by number of guesses. I would like entries with identical number of guesses to also be sorted by time in ms, in descending order. Tried searching and found some similar Q's but couldn't really find a solution. Any pointers will be greatly appreciated! Feel free to comment on other parts of my code as well!
import java.util.*;
public class Game {
private static ArrayList<highScore> score = new ArrayList<highScore>();
private class highScore implements Comparable<highScore> {
int guessCount = 0;
double playerTime = 0;
String playerName;
public highScore (int guessCount, double playerTime, String playerName) {
this.guessCount = guessCount;
this.playerTime = playerTime;
this.playerName = playerName;
}
public String toString() {
String scoreList = (this.playerName + "\t\t" + this.guessCount + "\t\t" + this.playerTime);
return scoreList;
}
public int compareTo(highScore hs) {
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
return -1;
}
}
public static void main(String [] args) {
boolean playGame = true;
Scanner scan = new Scanner(System.in);
Game g = new Game();
while(playGame) {
g.start();
System.out.println("\nPlay again?");
String s = scan.nextLine();
if (s.equalsIgnoreCase("n")) {
System.out.print("Quitting...");
playGame = false;
}
}
}
public void start() {
int number = (int) (Math.random() * 1001 );
int guess = -1;
int guessCount = 0;
String guessStr, playerName;
String quit = "quit";
Scanner scan = new Scanner(System.in);
boolean play = true;
System.out.print("Welcome to the greatest guessing game of all time!" +
"\nGuess a number between 1-1000!" +
"\nType \"quit\" to quit.");
long startTime = System.currentTimeMillis();
System.out.println("\nDEBUG, nr is: " + number);
while (guess != number && play) {
try {
System.out.print("\nEnter your guess: ");
guessStr = scan.nextLine();
if (guessStr.equalsIgnoreCase("quit")) {
play = false;
System.out.println("Quitting...");
return;
}
guess = Integer.parseInt(guessStr);
if (guess <= 1 || guess > 1000) {
System.out.println("Invalid guess, won't count, try again!");
}
if (guess < number) {
System.out.println("Too low, try again!");
guessCount++;
}
if (guess > number) {
System.out.println("Too high, try again!");
guessCount++;
}
}
catch(NumberFormatException e) {
System.out.println("Sorry, only numbers. Try again!");
}
catch (InputMismatchException ex) {
System.out.println("Sorry, only numbers. Try again!");
}
}
if (guess == number) {
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Nice, the correct number is " + number + "!");
System.out.print("You nailed it after " + (int)(gameTime)/1000 + " seconds and " + guessCount + " tries!");
System.out.println("\nEnter your name!");
playerName = scan.nextLine();
score.add(new highScore(guessCount, gameTime, playerName));
Collections.sort(score);
System.out.println("Name ------- Guesses -------- Time in ms");
for (highScore h: score) {
System.out.println(h);
}
}
}
}
You just need to modify your compareTo method to consider the equality case also. And then move to the next comparison: -
public int compareTo(highScore hs) {
if (this.guessCount == hs.guessCount) {
return (new BigDecimal(this.playerTime)).compareTo(
new BigDecimal(hs.playerTime)
} else {
return Integer.valueOf(this.guessCount).compareTo(
Integer.valueOf(hs.guessCount));
}
}
The compareTo() method of highScore has to be implemented as below
public int compareTo(highScore hs)
{
if (((Integer)this.guessCount).compareTo(((Integer)hs.guessCount)) > 0)
return 1;
else
{
if(this.guessCount == hs.guessCount)
{
if(this.playerTime > hs.playerTime)
{
return 1;
}
else
{
return -1;
}
}
return -1;
}
}
- Whenever you need to sort on the basis of more than 1 attributes, go for java.util.Comparator Interface.
- Use the compare() method of Comparator<T> along with Collections.sort(List l, Comparator c) to sort you list.