Arrays

Arrays are

  • Objects that can store more objects
  • Can store objects or primitive data-type
  • There are built-in array and Arraylist
  • ArrayLists which need you to import java.util.Collections
Properties Built-in Arrays ArrayList
Length The length is defined and constnat. Accesed by array.length The length will douolbe if there isn't enough space. array.size() is used to find the length
Index To get an index, use array[i] To use an index, use array.get(i)
Changing Values You can assign values at an index. Like so,
array[i]=2;
You can either add values with add(i,2) or add(2) or replace a certain value set(i,2)
Removing Values Can't remove indexes arrays can only be set to something else like null or 0 You can use Array.remove(i), which removes index i in the arrayList

Example

On the right you will see code from my Candidate Class. I chose this code to highlight the key differences between arrays and arrayLists. Arrays are used when the length is known whereas Arraylists are used when the length is not known. This is why we are using ArrayLists when getting Viable Candidates as there 0 to 10 viable candidates.

Copy

/*
Name: George Postica
Date: March 20, 2024
Teacher: Ms.Krasteva
Descritpion: The CandidateList class where I made all the functionality for the Test
*/
import java.util.*;
public class CandidateList{
    private Candidate[] myCList;
    //constructor
    public CandidateList(Candidate[] list){
        //transfering all values from one class to another instead of assigning same memory
        myCList= new Candidate[list.length];
        for(int i=0;i<list.length;i++){
            myCList[i]=list[i];
        }
    }
    
    public void computeVotePercents(){
        double allVotes=0.0;
        for(int i=0;i<myCList.length;i++){
            allVotes+=myCList[i].getNumVotes();
        }
        
        for(int i=0;i<myCList.length;i++){
            double percentage= (myCList[i].getNumVotes()/allVotes)*100.0;
            myCList[i].setVotePercent(percentage);
        }
    }
    //gives a list of viables candidates (10% or higher voting)
    public ArrayList<Candidate> getViableList(){
    
        ArrayList<Candidate> possCands= new ArrayList<Candidate>();
        for(int i=0;i < myCList.length;i++){
            //checks to see if the vote precent is higher than 10% then adds to list
            if(myCList[i].getVotePercent()>=10.0){
                possCands.add(myCList[i]);
            }
        }
        //returns the list
        return possCands;
    }
    public void printViable(){
        //uses pervious method to find the viable candidates
        ArrayList <Candidate> possCands=getViableList();
        //prints out viable candidates
        for(int i=0;i < possCands.size();i++){
            Candidate x=possCands.get(i);
            System.out.println(x.getName()+" "+x.getVotePercent());
        }
    }
}