Sorting Multiple ArrayLists Advice? - java

Hey there guys and gals.
Background:
I'm working on a high score program for homework that asks for 5 names and 5 scores. After the names with the corresponding scores are entered the program sorts the two ArrayLists by highest score. Finally it displays the names with their scores in sorted order.
Question:
I'm having the devil of a time trying to sort the ArrayLists , do you any advice on sorting ArrayLists ?
Code:
import java.util.*;
public class Assignment6
{
public static void main(String args[])
{
ArrayList<String> names = new ArrayList();
ArrayList<Integer> scores = new ArrayList();
initializeArrays(names, scores);
//sortArrays(names, scores);
displayArrays(names, scores);
}
public static void initializeArrays(ArrayList names, ArrayList scores)
{
Scanner in = new Scanner(System.in);
for(int i=0; i<5; i++)
{
System.out.println("Enter the name for score # " + (i+1) + ": ");
names.add(in.next());
System.out.println("Enter the score for score # " + (i+1) + ": ");
scores.add(in.next());
}
}
public static void sortArrays(ArrayList names, ArrayList scores)
{
for(int i=0; i<5; i++)
{
if(scores[i] < scores[i+1])
{
Collections.swap(scores,a, b);
Collections.swap(names,a, b);
}
}
}
public static void displayArrays(ArrayList names, ArrayList scores)
{
System.out.println("Top Scorers: ");
System.out.println(names);
System.out.println(scores);
}
}

Create one object with fields: name and score with implements Comparable.
Then having ONLY one ArrayList use Collections.sort(list);

You can wrap both score and name into one object and store it in a list.
class Result implements Comparable<Result>{
private String name;
private int 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;
}
#Override
public int compareTo(Result other) {
return this.score - other.score;
}
}
Now you can use Collections.sort(List<Result>) to sort them out based on the highest score.

ok, do you want to print something like that A-{Bob, Alex, ...}, where Bob is a name and A is scope, you can do it using one object as described by Alex, but if its home work I think your teacher want to see some comuter science data structure, in that case is Associative_array will be better. You can implement it by your side or use java implementation. Java provide us Map [T, V] , and implementation, for your case is TreeMap, where T - is scope and V - is a List of the Name because a lot of people can have the same scope.
So, result structure will be like that
Map<String, List<String>> sortedScopes = new TreeMap<>();
and using :
List<String> names = sortedScopes.get(scope);
if(names == null){
names = new ArrayList<>();
sortedScopes.put(scope, names);
}
names.add(name)
In that solution you will have just a 2 methods initialize and display,
Sorting by scope will execute on demand

Related

How to sort map without using comparable and Comparator Interface? How to write Custom Sorting?

Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.
I have created class Studnt
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
//Getter setter
}
Main class
public class StudentData {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enetr the number of Student");
int totalStudent = sc.nextInt();
Map<Integer,Student> map = new TreeMap<Integer,Student>();
for(int i =0;i<totalStudent;i++) {
Student ss = new Student();
System.out.println("Enter the Student roll number");
ss.setRollNumber(sc.nextInt());
System.out.println("Enter the Student Name");
ss.setName(sc.next());
System.out.println("Enter the m1 marks ");
ss.setM1(sc.nextInt());
System.out.println("Enetr the m2 marks ");
ss.setM2(sc.nextInt());
System.out.println("Enter the m3 marks ");
ss.setM3(sc.nextInt());
ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());
map.put(ss.getTotMarks(),ss);
ss=null;
}
//stdList.forEach(System.out::print);
for(Map.Entry<Integer,Student> m :map.entrySet()) {
System.out.println(m);
}
}
}
Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate
output
6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]
9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]
the only unique totMarks stored in the map
Since you can't use existing Comparator or sorting algorithms, you need to do it on your own. I have implemented a static function lessOrEqual which accepts 2 Student instances, compares them and returns whether or not s1 is less or equal to s2. larger(Student s1, Student s2) which returns true ONLY IF s1 is larger than s2. There can be many different ways of doing this, it's really up to you as it's just a comprison. The function first checks the grades, if the grades match, it will then check the name and return accordingly.
EDIT: As you can see I replaced lessOrEqual with larger since the selection sort I'm using needs to find larger. It's the same effect, I only did it for better readability of the sort.
Then I implemented another static function that accepts ArrayList<Student>, sorts it and returns it sorted. The sorting algorithm used is very basic: Selection sort. It's O(N^2) which isn't efficient, but I did it for the sake of simplicity in the demo below.
Code:
import java.util.ArrayList;
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
public static boolean larger(Student s1, Student s2){
if(s1.totMarks < s2.totMarks) return false;
else if (s1.totMarks > s2.totMarks) return true;
// compare names
else return s1.name.compareTo(s2.name) > 0;
}
public static ArrayList<Student> sortSelection(ArrayList<Student> list){
for(int i=0; i<list.size(); i++){
for(int j=i+1; j< list.size(); j++){
if(larger(list.get(i), list.get(j))){ // swap
Student temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
}
return list;
}
//Getter setter
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotMarks(){
return totMarks;
}
public void setTotMarks(int totMarks){
this.totMarks = totMarks;
}
#Override
public String toString(){
return String.format("Name: %20s - Total Marks: %3d", name, totMarks);
}
public static void main(String[] args){
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student s4 = new Student();
s1.setName("John Smith");
s1.setTotMarks(98);
s2.setName("Jack Smith");
s2.setTotMarks(98);
s3.setName("Adam Noob");
s3.setTotMarks(100);
s4.setName("Ved Parkash");
s4.setTotMarks(99);
ArrayList<Student> list = new ArrayList<>();
list.add(s4);
list.add(s3);
list.add(s1);
list.add(s2);
System.out.println("Array before sorting:");
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).toString());
}
Student.sortSelection(list);
System.out.println("Array after sorting:");
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).toString());
}
}
}
Output:
Array before sorting:
Name: Ved Parkash - Total Marks: 99
Name: Adam Noob - Total Marks: 100
Name: John Smith - Total Marks: 98
Name: Jack Smith - Total Marks: 98
Array after sorting:
Name: Jack Smith - Total Marks: 98
Name: John Smith - Total Marks: 98
Name: Ved Parkash - Total Marks: 99
Name: Adam Noob - Total Marks: 100
Notes:
1) See the order of addition of Students into the list, it's 4,3, 1 then 2. This is to prove that it sorts according to name when the grades match (Jack Smith vs John Smith).
2) I hardcoded the students to make for a better demo.
3) As you may notice, I'm not setting any of the other variables since the question is solely about sorting, and the only contributing variables to sorting are: name and totMarks. You will have to do the rest.
4) I am using ArrayList, but this isn't limited to that, with simple changes you can use it on a normal Student[] array.
5) The function larger doesn't have to be static, you can make it a member function and use it differently. For example, the code above would change to:
public boolean larger(Student other){
if(totMarks < other.totMarks) return false;
else if (totMarks > other.totMarks) return true;
// compare names
else return name.compareTo(other.name) > 0;
}
public static ArrayList<Student> sortSelection(ArrayList<Student> list){
for(int i=0; i<list.size(); i++){
for(int j=i+1; j< list.size(); j++){
// comparison way changes accordingly
if(list.get(i).larger(list.get(j))){ // swap
Student temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
}
return list;
}
In the interests of Keeping it simple (i.e. the KISS principle) and explaining my "hint" relating to a compound key, following is the worked example.
The "key" to the solution is to let the tree sort the data naturally (not, IMHO, to add to the code making it more complex by providing a manual sort). Thus the student class needs to return a key that the tree can naturally sort.
To produce the desired sort result, the key for the Tree is (total Marks, student name).
Here is the revised Student class (minus getters and setters, but I did add a new constructor to make life easy for me):
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
//Getter setter
public Student() {
}
public Student(String name, Integer rollNumber, int m1, int m2, int m3) {
this.name = name;
this.rollNumber = rollNumber;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.totMarks = m1 + m2 + m3;
}
public String getKey() {
// return String.format("%d-%s", totMarks, name); // WRONG!
return String.format("%04d-%s", totMarks, name); // Right
}
public String toString() {
return String.format("%06d: %s - %d", rollNumber, name, totMarks);
}
}
Note there is a commented out line of code in the getKey method with the comment WRONG. This relates to my hint of testing with single digit scores. Try swapping out the two lines of code to see the correct and incorrect result.
Here is the main, I removed all of the Scanner stuff - again to make life easy for me. Hopefully you can follow it and add back in your scanner loop.
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class StudentData {
public static void main(String[] args) {
// Initialise a list of students (as I don't want to rekey all the details each
// time I run the program).
List<Student> studentList = Arrays.asList(
new Student("Fred", 1, 2, 2, 2), /* Score of 6 */
new Student("John", 2, 2, 3, 3), /* Score of 8 */
new Student("Jane", 3, 20, 25, 30), /* Score of 75 */
new Student("Julie", 4, 20, 15, 10) /* Score of 45 */
// add as many new students as you like, and reorder them
// as much as you like to see if there is any difference in the
// result (there shouldn't be).
);
// Note the key of the tree is of type String - not Integer.
// This is the heart of the algorithm, the tree will be "sorted"
// on the natural key provided. This "natural key" is in fact
// a compound key that is generated by combining the total score
// and the student name.
Map<String,Student> map = new TreeMap<String,Student>();
for (Student ss : studentList) {
map.put(ss.getKey(),ss);
}
//stdList.forEach(System.out::print);
for(Map.Entry<String,Student> m :map.entrySet()) {
System.out.println(m);
}
}
}
I hope you agree that this is a simpler solution. There is also a potential performance benefit as the students are sorted as they are being loaded into the tree (i.e. once). The performance of this sorting is, I think, log(n). Sort on retrieval will likely be n log(n) or worse.
Instead of storing the values as student store them as a map of (name, student), so that when a student with the same marks is encountered, it is added to the map.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enetr the number of Student");
int totalStudent = sc.nextInt();
Map<Integer, Map<String, Student>> map = new TreeMap<>();
for(int i =0;i<totalStudent;i++) {
Student ss = new Student();
System.out.println("Enter the Student roll number");
ss.setRollNumber(sc.nextInt());
System.out.println("Enter the Student Name");
ss.setName(sc.next());
System.out.println("Enter the m1 marks ");
ss.setM1(sc.nextInt());
System.out.println("Enetr the m2 marks ");
ss.setM2(sc.nextInt());
System.out.println("Enter the m3 marks ");
ss.setM3(sc.nextInt());
ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());
Integer key = ss.getTotMarks();
if (map.get(key) == null){ // if this is a new key in the map, then create a new TreeMap and put it
final TreeMap<String, Student> nameAndStudentMap = new TreeMap<>();
nameAndStudentMap.put(ss.getName(), ss);
map.put(key, nameAndStudentMap);
}else { // if the key already existed, then get the map stored and add to it.
map.get(key).put(ss.getName(), ss);
}
}
//stdList.forEach(System.out::print);
for(Map.Entry<Integer,Map<String, Student>> m :map.entrySet()) {
for (Map.Entry<String, Student> nameAndStudent : m.getValue().entrySet()) {
System.out.println(m.getKey() + " = " + nameAndStudent.getValue());
}
}
}

Wrong object is being deleted from array

My program is not having any errors, but the wrong student is being deleted from my course (an array) and I'm not sure why. If I change the name to the 3rd student (James), I get an NPE error on the dropStudent lines. I think it might have something to do with my dropStudent method, but I think it should loop through course with index equal to 'i' and when that index equals the name, it becomes null leaving the other 2 students.
I'll post the code below along with my output.
package reviseCourse;
import java.util.*;
public class ReviseCourse {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create new course to enroll students in
ReviseCourse cs216 = new ReviseCourse("cs216");
// Add 3 students to the course
cs216.addStudent("William");
cs216.addStudent("Angela");
cs216.addStudent("James");
// Drop the student William from the course
cs216.dropStudent("William");
// Print course name and students individually by looping through the numberOfStudents
System.out.println("The students in the course " + cs216.getCourseName() + " are:");
for (int i = 0; i < cs216.getNumberOfStudents(); i++) {
System.out.print(students[i] + " ");
}
}
private String courseName;
private static String[] students = new String[100];
private String[] course = new String[students.length + 1];
private int numberOfStudents;
public void populateCourse() {
for (int i = 0; i < students.length; i++) {
course[i] = students[i];
System.out.println(course[i]);
}
}
public ReviseCourse(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
for (int i = 0; i < students.length; i++) {
course[i] = students[i];
}
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < course.length; i++) {
if (course[i].equals("William")) {
course[i] = null;
numberOfStudents--;
break;
}
}
}
// Deletes all students from the course
public void clear() {
numberOfStudents = 0;
}
}
Output:
The students in the course cs216 are:
William Angela
dropStudent modifies the course array, but not the student array, which you're printing from. The bigger issue is that you're just assigning null to the student you want to delete, but decrementing the number of students, so even if you print from courses you won't get the right output.
If the array of students is:
William | Angela | James : numStudents = 3
Then dropping William makes the array:
null | Angela | James : numStudents = 2
Now if you try to print the students, your code will will print the first two elements, which are null and Angela. Probably not what you want.
You should either be shifting over elements when you drop students, so that the array would instead look like:
Angela | James | null : numStudents = 2
After dropping William, or instead of reinventing the wheel just use ArrayList.
In your dropStudent method:
if (course[i].equals("William")) {
So this method is only ever going to drop William, no matter which student is actually passed into it.
Additionally, you are looping through the students array, but dropStudent only removes students from the course array.
public void dropStudent(String student) {
for (int i = 0; i < course.length; i++) {
if (course[i].equals(student) {
course[i] = null;
numberOfStudents--;
//can re order to keep the array tidy, ie go with for if you find a
//null then set it to be the next value in the array; thus will keep
//array management more efficient
break;
}
}
}

java - find the max value from a linked list

Disclaimer: I am a very early student and am struggling to learn java. Please tell me if I'm leaving out any important information.
I am writing a program that prompts the user to do various operations to a linked list (add, remove, change value, etc.) but rather than storing a string or some primitive data type I am storing objects of type Student (which basically contains a string for the name of the student and an integer for their test score) and am stuck on how to find the maximum test score since I can't just find the highest Student.
Any help would be appreciated.
Well you can have two variables, one as the currentScore, and another as the newScore. And then traverse through each student object, get the test value, and then compare. If the new score is lower, then keep current. If new score is higher, replace current score with new score, and keep traversing. When you traverse the list, you have the highest score
You can iterate over the list as other answers described or you can use Collections.max method. To use this method your Student class should implement comperable interface.
public class Student implements Comparable<Student>
and you need to add compareTo method to the class:
#Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}
Now when you write Collections.max(list) you will get the Student with the highest score.
I wrote a simple program that matched your case.
Main Class:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}
The student constructor class:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}
The above program produce result as follows:
Highest score is: Peter
Score: 10

Arrays with mutliple elements in java and other Issue

Having problems linking this program to this class. The program takes in a set of String + double arrays and goes through a series of sorts to yield a result. Our instructions are to sort then by name and sort then by price.
Main problem is that the Strings are displaying as hexadecimal eg(Item#4fjipe) etc.
Second problem is my sorts. I just have no idea how to make them work. Please help if at all possible. I will include both the class and the program. Bear in mind they are 2 different .java working together. I'm a beginner, by the way.
public class Item
{
private String itemName; // hold the name of the item
private double itemPrice; // hold the price of the item
public Item(String s, double p) // Constructor
{
itemName = s;
itemPrice = p;
}//end constructor
public void setName(String n)
{//method to set the item name
itemName = n;
}//end method
public String getName()
{//method to get the item name
return itemName;
}//end method
public double setPrice(double p1)
{//method to set the price of the item
itemPrice = p1;
return itemPrice;
}//end method
public double getPrice()
{//method to get the price of the item
return itemPrice;
}//end method
}//end class
AND NOW THE OTHER BEGINS. THIS ONE IS STILL A HOT MESS.
import javax.swing.*;
import java.util.Arrays;
public class CoffeeDriver
{
public static void main (String[] args)
{
Item[] itemArray = new Item[5]; // Array of type Item declaration
boolean loopControl = false; //variable for control of our loop
while (!loopControl)
{
itemArray[0] = new Item("Coffee", 1.00);
itemArray[1] = new Item("Water", 2.00);
itemArray[2] = new Item("Milk", 1.50);
itemArray[3] = new Item("Bagel",1.25);
itemArray[4] = new Item("Donut", 0.75);
String input = JOptionPane.showInputDialog(null, "Welcome to Wings Coffee Shop. We have a great list items on our menu. \nWould you like to see these items sorted by name of by price? (n/p):");
if(input.equals("n"))
{
sortName(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}//end if
else if(input.equals("p"))
{
sortPrice(itemArray);
JOptionPane.showMessageDialog(null, itemArray);
}
else
{
loopControl = true;
}
}//end while
}//end main
public static void sortName(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortName
public static void sortPrice(Item[] itemArray)
{
int n = itemArray.length;
Item temp = new Item("",0);
for (int i =0; i < n; i++)
{
for(int j =1; j<(n-1); j++)
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
if(itemArray[j+1] == itemArray[j])
{
temp.setPrice(itemArray[j+1].getPrice());
temp.setName(itemArray[j+1].getName());
itemArray[j+1].setPrice(itemArray[j].getPrice());
itemArray[j+1].setName(itemArray[j].getName());
itemArray[j].setPrice(temp.getPrice());
itemArray[j].setName(temp.getName());
temp = itemArray[j+1];
itemArray[j+1] = itemArray[j];
itemArray[j] = temp;
JOptionPane.showMessageDialog(null, itemArray);
}//end if
}//end inner for
}//end outer for
}//end sortPrice
}//end class
You need to override the toString method in your Item class. You could use:
#Override
public String toString() {
return "Item [itemName=" + itemName + ", itemPrice=" + itemPrice + "]";
}
As you need to have 2 separate methods to sort by name and by price, you could use a custom comparator for both cases, using the appropriate field to compare against. Have a look at Arrays.sort() for doing the actual sorting.
'Item#4fjipe' is the object reference as provided by the default implementation of Object.toString() - read the API for reference.
A hexadecmial literal in Java start swith 0x, e.g. 0x10.
For your specific problem, you have a data object that you wish to sort in 2 different ways. Read the API documentation for Comparator and Comparable. Then check the Collections API to see which collections might offer you sorting.

search arraylist by id-java

The following program asks to give the number of the players and their names. I want to put the names in a arraylist and return them by their id.
private static ArrayList<Player>Playerlist=new ArrayList<Player>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s;
{
System.out.printf("number of players(2 -4)? ");
int p = scanner.nextInt();
scanner.nextLine();
for(int i=0;p>4 || p<2;i++)
{
System.out.printf("only 2-4 players.\n");
System.out.printf("number of players(2 -4)?");
p = scanner.nextInt();
scanner.nextLine();
}
Player pl=new Player();
int m=1;
for(int k=1;k<=p;k++)
{
System.out.printf("give the name of the player %d: ",k);
s= scanner.nextLine();
pl.setName(s,m);
System.out.printf(pl.getName());
Playerlist.add(pl);
m++;
}
public class Player {
private String name;
private int id;
public Player () {
}
Player(String val,int k) {
this.name = val;
this.id=k;}
/**
* getName
*
*/
public String getName () {
return name;
}
/**
* setName
*/
public void setName (String val,int k) {
this.name = val;
this.id=k;
}
public void displayStudentDetails(){
System.out.println("ID is "+id);
System.out.println("Name is "+name)};
i dont know how to do the search by id...i have tried many things but they didnt work....
A better solution would be to use a HashMap<Integer, String>, with the id being the key and the name being the value. Then you can search easily:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Robert");
map.put(2, "Jeff");
Then to search:
String name = map.get(1); // will return "Robert"
Edit: Ok, if you need more data than just name, like score, you will need to create a data type. Like:
public class Player {
private String name;
private int score;
// etc.
public Player(String name, int score) {
this.name = name;
this.score = score;
}
}
And then you can add objects of this type to the map like:
map.put(1, new Player("Robert", 10));
Ignoring the fact that you should have classes in different files without global variables at this time...
/**
* Searches the PlayerList Arraylist for a Player having the ID of the parameter passed
*/
public Player searchByID(int id) {
//Do some sort of check on id to ensure its valid?
for (int i = 0; i < PlayerList.size(); i++) {
if (PlayerList.get(i).getID() == id) {
return PlayerList.get(i);
}
}
return null;
}
ArrayList is probably the wrong data structure. If you want to retrieve the elements in id order, you want a HashMap if the ids are all regular in the sense that you can be sure of things like "ids are 1 to 10 and there are no unused ids". If the id set is sparse, you'll want a to use TreeMap or TreeSet depending on your other use cases.
If the situation where you need to get the player by ID is based exactly on how your code is adding players, then you can just do:
public Player getPlayerById(int id)
{
return PlayerList.get(id - 1);
}
Since you are assigning player ids linearly starting at 1 for the first player. If you are modifying or otherwise changing the order of players and ids then you will need to use one of the other suggestions (but if you are not doing that then this is the most optimized solution).
Note: The code above will throw an ArrayIndexOutOfBoundsException if the id does not exist in the player list, do you may want to modify the code depending on how you want to handle that.

Categories

Resources