Given that there is an ArrayList named list that contains 5 Player objects, writ
ID: 3562294 • Letter: G
Question
Given that there is an ArrayList named list that contains 5 Player objects, write the code to call and output the getPoints() method of the third element in list. The getPoints() method accepts no parameters and returns an int value.
ArrayList list = new ArrayList();
int num = 12;
Write the code to add the value contained in num to the ArrayList. Remember that ArrayLists can only hold objects.
Complete method getTotalPoints, which returns the total points of a given set of objects.
//precondition: list is a non-empty ArrayList containing Player objects.
//postcondition: returns the total of the int values stored in the points
field of the Player objects contained inside the ArrayList.
//the Player class contains method getPoints() which returns the point field
of the Player object.
public static double getTotalPoints (ArrayList list){
Explanation / Answer
// Given that there is an ArrayList named list that contains 5 Player objects, write the code to call and output the getPoints() method of the third element in list. The getPoints() method accepts no parameters and returns an int value.
// 3rd Player from list
1) Player player = (Player)list.get(2);
// invoke getPoints() on that 3rd Player
System.out.println("Player Points : "+player.getPoints());
2 )
// ArrayList list = new ArrayList();
//int num = 14;
//Write the code to add the value contained in num to the ArrayList. Remember that ArrayLists can only hold objects.
in this case int is Automatically Stored as Integer Object in List.
when we retrive from list TYPE CASTING to int is REQUIRED
if we dont want type casting then we will use GENERICS i.e Specific data should only allowed in List
list.add(num);
3)
public static double getTotalPoints (ArrayList list)
{
//precondition: list is a non-empty ArrayList containing Player objects.
if(list != null && list.size() > 0)
{
int totalPoints = 0;
for(Player player : list)
{
int playerPoints = player.getPoints();
totalPoints = totalPoints + playerPoints;
}
// return as double
return (double)totalPoints ;
}
// list doesn't contain any Objects
else
return 0.0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.