Speeding up/increasing performance of an Java array class - java

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.

Related

Hackerrank Wrong Answer

I was practicing my coding skills on hackerrank 30 days of code.While Solving Day 4 problem of classes and instances it showed wrong outcome.[enter image description here][1]
Expected Output:
https://i.stack.imgur.com/YOgMw.jpg
My Output:
https://i.stack.imgur.com/Ee27n.jpg
If you notice, there's an extra line in my code and it only comes when last input is old.
Can anyone tell how to fix this?
https://i.stack.imgur.com/jnPZZ.jpg
Here's my code:
import java.io.*;
import java.util.*;
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
this.age=initialAge;
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
if(age<0)
{ age=0;
System.out.println("Age is not valid,setting age to 0");
System.out.println("You are young.");
}
else if(age<13){
System.out.println("You are young.");}
else if(age>=13&&age<18){
System.out.println("You are a teenager.");}
else
{ System.out.println("You are old.");
}
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
Try this:
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge<0){
age = 0;
System.out.println("Age is not valid, setting age to 0.");
}else{
age = initialAge;
}
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
if(age<13){
System.out.print("You are young.");
System.out.println("");
}else if (age>=13 && age<18){
System.out.print("You are a teenager.");
System.out.println("");
}else {
System.out.print("You are old.");
System.out.println("");
}
}
public void yearPasses() {
// Increment this person's age.
age++;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
this is my try:
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge>=0) age=initialAge;
else{
age=0;
System.out.println("Age is not valid, setting age to 0.");
}
}
public void amIOld() {
if(age<13)System.out.println("You are young.");
if(age>=13 && age<18)System.out.println("You are a teenager.");
if(age>=18) System.out.println("You are old.");
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
This is the answer for HackerRank - 30 Days of Code - Day 4 classes and instances
import java.io.*;
import java.util.*;
public class Person {
    private int age;    
  
    public Person(int initialAge) {
        // Add some more code to run some checks on initialAge
          
          if (initialAge > 0) {
                age = initialAge;
            } else {
                System.out.println("Age is not valid, setting age to 0.");
                age = 0;
            }
    }
    public void amIOld() {
        // Write code determining if this person's age is old and print the correct statement:
        String output="";
        if (age < 13) {
            output="You are young.";
        }else if (age < 18) {
            output="You are a teenager.";
        }else {
            output="You are old.";
        }
        System.out.println(output);
    }
    public void yearPasses() {
        // Increment this person's age.
          age++;
    }
    public static void main(String[] args) { ... }
i have tried this and i have rectify this error by using the following code;
import java.io.;
import java.util.;
public class Person {
private int age;
public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if(initialAge<0)
{
this.age=0;
System.out.print("Age is not valid, setting age to 0.");
}
else
this.age=initialAge;
}
public void amIOld() {
// Write code determining if this person's age is old and print the correct statement:
System.out.println("");
if(age>=0 && age < 13){
System.out.print("You are young.");}
else if(age>=13 && age < 18){
System.out.print("You are a teenager.");}
else{
System.out.print("You are old.");}
}
public void yearPasses() {
// Increment this person's age.
age=age+1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}

How can I get my program back on track when printing out all student records?

import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.

Poker dice game, and I don't know why my methods have errors on them

public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int[] dice = new int[5];
resetDice(dice);
System.out.print("Your current dice: + dice");
rollDice(dice);
System.out.print(dice);
System.out.println();
promptForReroll(dice, inScanner);
System.out.println("Rerolling...");
rollDice(dice);
System.out.println("Your final dice: + dice");
System.out.println(getResult(dice)+"!");
}
private static void resetDice(int[] dice) {
int length = 5;
for(int i = 0; i < length; i++){
dice[i] = 0;
}
}
private static void rollDice(int[] dice) {
int i = 0;
int length = 5;
while(i < length) {
if(dice[i] == 0) {
int roll = (int)(Math.random()*6)+1;
dice[i] = roll;
i++;
}
}
}
private static String diceToString(int[] dice) {
String diceToString =("Your current dice: " +dice[0]+", " +dice[1]+ ", " +dice[2]+ ", " +dice[3]+ ", " +dice[4]);
return diceToString;
}
private static void promptForReroll(int[] dice, Scanner inScanner) {
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
int selection = inScanner.nextInt();
while(selection != -1){
if(selection > 4 || selection < -1){
System.out.println("Erorr: Index must be between 0 and 4 (-1 to quit)!");
}
else{
dice[selection] = 0;
}
System.out.println("Your current dice: " + dice);
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
selection = inScanner.nextInt();
}
System.out.println("Keeping remaining die...");
}
private static boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
}
private static String getResult(int[] dice) {
getCounts(dice);
}
private static int[] getCounts(int[] dice) {
int[] count = new int[6];
int i = 0;
int j = 0;
while(i<5){
while(j<5){
if(dice[i] == (j+1)){
count[j]++;
i++;
}
else{
i++;
}
j++;
}
}
return count;
}
I have written out the coding, and I think for the most part it may be right, but I can't run it because it has errors on my promptForPlayAgain method, and my getResult method. I don't know why there are errors on them.
You aren't returning anything if the user's input isn't "Y" or "N". You need to add an else case:
private static Boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
else
{
//Do something here to handle bad input.
}
}
Ideally though, you should be doing some kind of formatting and preverification of the input, like forcing the input to upper case before comparing.
And on getResult, you aren't returning anything. Add a return before the body of the function. That won't fix it though, since the return type of getValue doesn't match getResult. You're trying to return a int array as a string.
In the future, please include the actual error messages they you receive.

I'm getting an error here when I call my getChoice() method, and I don't know why

I'm getting an error where I call my getChoice() method, its saying variable footballTeam2 is already defined in the main method, why is that? Also am I calling my other method correctly?
Thanks in advance guys, really could use some help.
import java.util.Scanner;
public class FootballGame {
static Scanner keyboard = new Scanner(System.in);
static int arewedone = 0;
static String choice;
static FootballTeam team;
public static void main(String[] args) {
FootballTeam footballTeam1;
FootballTeam footballTeam2;
System.out.print("Enter a name for a team:");
footballTeam1 = new FootballTeam(keyboard.nextLine(), 0);
System.out.print("Enter a name for another team:");
footballTeam2 = new FootballTeam(keyboard.nextLine(), 0);
do{
System.out.println("Game Score:");
System.out.println(footballTeam1.getName() + ":" + footballTeam1.getScore());
System.out.println(footballTeam2.getName() + ":" + footballTeam2.getScore());
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
handleTeamScore(team);
}while(arewedone == 0);
}
public static String getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2) {
String input;
do {
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + " scored");
System.out.println("B:" + footballTeam2 + " scored");
System.out.println("C: game ended.");
System.out.println("?:");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("A")) {
choice = (footballTeam1 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = (footballTeam2 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("C")) {
System.out.println("Game Over");
arewedone++;
}
} while (!input.equals("A") && !input.equals("B") && !input.equals("C"));
return choice;
}
public static void handleTeamScore(FootballTeam team) {
int points;
do {
System.out.println("How many points were scored?");
System.out.print("?: ");
points = keyboard.nextInt();
if ((team.addScore(points)) == true) {
arewedone++;
} else {
System.out.println("That was an invalid option. Please try again.");
System.out.println("Hints:");
System.out.println("Touchdown = 6 points");
System.out.println("Field Goal = 3 points");
System.out.println("Safety = 2 points");
System.out.println("Extra Point = 1 point");
}
} while (arewedone == 0);
}
}
Here's my other class with the addscore method and getters and setters.
public class FootballTeam {
private String name;
private int score;
public static int TOUCHDOWN = 6;
public static int FIELD_GOAL = 3;
public static int SAFETY = 2;
public static int TWO_POINT_CONVERSION = 2;
public static int EXTRA_POINT = 1;
public FootballTeam(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean addScore(int points) {
if (points == TOUCHDOWN || points == FIELD_GOAL || points == SAFETY || points == TWO_POINT_CONVERSION || points == EXTRA_POINT) {
score = points + score;
return true;
} else {
return false;
}
}
}
Change the method call
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
to this:
choice = getMenuChoice(footballTeam1, footballTeam2);
EDIT:
You need to initialize FootballTeam team before calling handleTeamScore(team);:
team = new FootballTeam(...);
handleTeamScore(team);
Change this code block of getMenuChoice:
if (input.equalsIgnoreCase("A")) {
choice = (footballTeam1 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = (footballTeam2 + "");
arewedone = 0;
to this :
public static String getMenuChoice(...){
...
if (input.equalsIgnoreCase("A")) {
choice = "footballTeam1";
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = "footballTeam2";
arewedone = 0;
...
}
Now replace these two statements in main:
choice = getMenuChoice(footballTeam1, footballTeam2);
handleTeamScore(team);
to this:
choice = getMenuChoice(footballTeam1, footballTeam2);
if(choice != null) {
if(choice.equals("footballTeam1")){
team = footballTeam1;
}
if(choice.equals("footballTeam2")){
team = footballTeam2;
}
handleTeamScore(team);
}
You are calling your method wrongly
you should call it like this
choice = getMenuChoice1( footballTeam1, footballTeam2);
by calling it like this
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
you confusing compiler whether you are calling a method or declaring a new one. We dont require to type the type while calling the method its implicit always

Sorting highscore by time and number of guesses

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.

Categories

Resources