Question

(This program is to be done on Java) 7.5 ArrayLists Part 1 A significant limitation of...

(This program is to be done on Java)

7.5 ArrayLists Part 1

A significant limitation of the array is you cannot add or delete elements from the array. The size is fixed and you can only do workarounds. An example is the following:

public class Ex_7_5_Prep
{
    public static void main(String[] args)
    {
        int[] intArray = { 5, 10, 15, 20 };

        printArray(intArray);

        intArray = addNewElement(intArray, 25);

        printArray(intArray);
    }

    public static int[] addNewElement(int[] originalArray, int newInt)
    {
        // Create new array one element larger than the original array
        int[] newArray = new int[originalArray.length+1];

        // Copy the data from the original array to the new array
        for ( int i = 0; i < originalArray.length; i++ )
        {
            newArray[i] = originalArray[i];
        }

        // Add the new element to the array
        newArray[newArray.length-1] = newInt;

        return newArray;
    }

    public static void printArray(int[] intArray)
    {
        for ( int i = 0; i < intArray.length; i++ )
        {
            System.out.print(intArray[i] + " ");
        }
        System.out.println();
    }
}

If the new array were created within the main() method, the program would experience an increase in memory usage that may not go away until the program ends. Once a variable is declared, it does not go away until the end of the scope. In the example above, we move from the main() method scope into the addNewElement() method scope to create the new array and copy the data. When we leave the addNewElement() method, everything within that scope is sent to the garbage collector for recovery of resources.

The approach mentioned above has been packaged into what is known as an ArrayList. The underlying code for an ArrayList is much more complex than the example above, but it essentially performs similar steps.

To delcare an ArrayList of Strings, you will use the following syntax:

ArrayList<String> countryNames = new ArrayList<>();

If you wanted to use integers, you would have to use the complex data type:

ArrayList<Integer> goldMedals = new ArrayList<>();

If you tried to use int instead of Integer, you would receive an error when compiling and IntelliJ would say you cannot use primitive data types. A complex data type is an enhanced version of your primitive data types but allows you to perform a variety of methods on the data.

Although you can have an ArrayList of ArrayLists create something similar to the multi-dimensional arrays, it would be better off to use classes, which is the example we will use here.

Within your main() method, add the following code:

ArrayList<OlympicTeam> olympicTeams = new ArrayList<>();

Create a new file named OlympicTeam.java along with the related class. Within the class you will have 4 variables: teamName, totalGoldMedals, totalSilverMedals, and totalBronzeMedals. Choose the appropriate data types, make the variables private, and create the related getter and setter methods.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the code for the above assignment.

Feel free to comment on any doubt and give thumbs up!

Additionally, I have added comments to understand the code better.

There are 2 files that contain the code.

1. OlympicTeam.java which contains the OlympicTeam class with proper members variables and getters/setters method in it.

2. Main.java which contains the main method and ArrayList Object.

Code for OlympicTeam.java

class OlympicTeam {

private String teamName;

private int totalGoldMedals;

private int totalSilverMedals;

private int totalBronzeMedals;

public OlympicTeam(String teamName, int gold, int silver, int bronze) {

this.teamName = teamName;

totalGoldMedals = gold;

totalBronzeMedals = bronze;

totalSilverMedals = silver;

}

// Setters methods

void setTeamName(String name) {

teamName = name;

}

void setTotalGoldMedals(int gold) {

totalGoldMedals = gold;

}

void setTotalSilverMedals(int silver) {

totalSilverMedals = silver;

}

void setTotalBronzeMedals(int bronze) {

totalBronzeMedals = bronze;

}

// getters

String getTeamName() {

return teamName;

}

int getTotalGoldMedals() {

return totalGoldMedals;

}

int getTotalSilverMedals() {

return totalSilverMedals;

}

int getTotalBronzeMedals() {

return totalBronzeMedals;

}

}

Code for Main.java

import java.util.ArrayList;

public class Main

{

public static void main(String[] args) {

// creating ArrayList which consists of OlympicTeam objects

ArrayList<OlympicTeam> olympicTeams = new ArrayList<>();

// creating five objects of type OlympicTeam

OlympicTeam team1 = new OlympicTeam("Japan", 5, 6, 4);

OlympicTeam team2 = new OlympicTeam("America", 6, 2, 4);

OlympicTeam team3 = new OlympicTeam("India", 5, 7, 2);

OlympicTeam team4 = new OlympicTeam("China", 3, 6, 8);

OlympicTeam team5 = new OlympicTeam("Australia", 7, 9, 2);

// demonstration of getters and setters method

team1.setTotalBronzeMedals(8);

team1.setTotalGoldMedals(7);

team1.setTotalSilverMedals(5);

// adding all five objects in ArrayList

olympicTeams.add(team1);

olympicTeams.add(team2);

olympicTeams.add(team3);

olympicTeams.add(team4);

olympicTeams.add(team5);

// iterating over the olympicTeams to print information of each team using getters

for (OlympicTeam olympicTeam : olympicTeams) {

System.out.println("Team Name: " + olympicTeam.getTeamName() );

System.out.println("Number of Gold Medals: " + olympicTeam.getTotalGoldMedals());

System.out.println("Number of Silver Medals: " + olympicTeam.getTotalSilverMedals());

System.out.println("Number of Bronze Medals: " + olympicTeam.getTotalBronzeMedals());

System.out.println();

}

}

}

Screenshot of the test run

Thank You!

Add a comment
Know the answer?
Add Answer to:
(This program is to be done on Java) 7.5 ArrayLists Part 1 A significant limitation of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PrintArray vi Create a class called PrintArray. This is the class that contains the main method....

    PrintArray vi Create a class called PrintArray. This is the class that contains the main method. Your program must print each of the elements of the array of ints called aa on a separate line (see examples). The method getArray (included in the starter code) reads integers from input and returns them in an array of ints. Use the following starter code: //for this program Arrays.toString(array) is forbidden import java.util.Scanner; public class PrintArray { static Scanner in = new Scanner(System.in);...

  • IN JAVA please Given a sorted array and a target value, return the index if the...

    IN JAVA please Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. Your code will be tested for runtime. Code which does not output a result in logarithmic time (making roughly log(2) N comparisons) will fail the tests. A sample main function is provided so that you may test your code on sample inputs. For testing purposes, the...

  • Please complete the following programming with clear explanations. Thanks! Homework 1 – Programming with Java: What...

    Please complete the following programming with clear explanations. Thanks! Homework 1 – Programming with Java: What This Assignment Is About? Classes (methods and attributes) • Objects Arrays of Primitive Values Arrays of Objects Recursion for and if Statements Selection Sort    Use the following Guidelines: Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc.) Use upper case for constants. • Use title case (first letter is upper case) for classes. Use lower case with uppercase...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • JAVA Write a program which will read a text file into an ArrayList of Strings. Note...

    JAVA Write a program which will read a text file into an ArrayList of Strings. Note that the given data file (i.e., “sortedStrings.txt”) contains the words already sorted for your convenience. • Read a search key word (i.e., string) from the keyboard and use sequential and binary searches to check to see if the string is present as the instance of ArraryList. • Refer to “SearchInt.java” (given in “SearchString.zip”) and the following UML diagram for the details of required program...

  • last question : Don't be negative and source Code : of don't be negative Repeat the...

    last question : Don't be negative and source Code : of don't be negative Repeat the assignment "don't be so negative" except solve the problem using recursion. Specifically, create an array of 10 random integers between -10 and +10 then create a method say "findNegatives" that takes as input parameters the array, and possibly other parameters, then calls itself (direct recursion); method find Negatives( ...method parameters here...) ...some stopping criteria... find Negatives(...method parameters here...) Output: Array position #0 #1 Value...

  • Money Lab using arraylists in Java Using the Coin class below create a program with the...

    Money Lab using arraylists in Java Using the Coin class below create a program with the following requirements Create an arraylist that holds the money you have in your wallet. You will add a variety of coins(coin class) and bills (ones, fives, tens *also using the coin class) to your wallet arraylist. Program must include a loop that asks you to purchase items using the coins in your wallet. When purchasing items, the program will remove coins from the arraylist...

  • The Language is Java GenericMethodTest (20) Download the OverloadedMethods.java program. Replace all the methods except main...

    The Language is Java GenericMethodTest (20) Download the OverloadedMethods.java program. Replace all the methods except main with a single generic method that produces the same output. Call the new file GenericMethodsTest.java. OverloadMethods.java: // Printing array elements using overloaded methods. public class OverloadedMethods { // method printArray to print Integer array public static void printArray(Integer[] inputArray) { // display array elements for (Integer element : inputArray) { System.out.printf("%s ", element); } System.out.printf("\n"); } // method printArray to print Double array public...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT