So I'm working on an assignment for my AP Computer Science Class dealing with ArrayLists. For #13 and 14 I am supposed to increment each ArrayList element by a random number between 0 and 20 (inclusive). I don't understand why I cannot use the (ArrayList.set()) method to increment my ArrayList elements. Thank you in advance!
import java.util.Collection; //Driver Class
import java.util.Random;
import java.util.ArrayList;
import java.util.Random;
public class MusicDownloads {
public static void main(String[] args) {
ArrayList < DownloadInfo > music = new ArrayList < DownloadInfo > ();
music.add(new DownloadInfo("So What")); //2
music.add(new DownloadInfo("Blue in Green"));
music.add(new DownloadInfo("Night in Tunisia"));
music.add(new DownloadInfo("Fly Me to the Moon"));
music.add(new DownloadInfo("Come Fly With Me"));
music.add(new DownloadInfo("This Town"));
music.add(new DownloadInfo("Flamenco Sketches"));
int addNum = 0;
Random rand = new Random();
for (int i = 0; i < music.size(); i++) {
addNum = 0;
addNum = (int) Math.random() * 20; //13
music.set(i, music.get(i).addNumDL(addNum));
}
System.out.println("Num 13/14");
for (int i = 0; i < music.size(); i++) {
System.out.println(music.get(i)); //14
}
}
}
public class DownloadInfo //Object Class
{
private String title = "";
private int numDownloads = 0;
public DownloadInfo(String t) {
title = t;
}
public String getSongTitle() {
return title;
}
public void addNumDL(int addNum) {
numDownloads = addNum + numDownloads;
}
public int getnumDownloads() {
return numDownloads;
}
public String toString() {
return ("Song title: <" + title + "> " + " <Number of times downloaded: " + numDownloads + ">");
}
}
set()method does not add a new element, it replaces the element at the specified position: docs.oracle.com/javase/1.5.0/docs/api/java/util/…