Java arrays have a significant shortcoming. They cannot be resized after they ha
ID: 3701296 • Letter: J
Question
Java arrays have a significant shortcoming. They cannot be resized after they have been instantiated. This can be a major problem, since you often don't know how many elements a list of items will need when creating it One strategy is to start out with a small number of elements, then create a larger array when more space is needed, and copy the old array into the new one. This can be a hassle, and complicates the code, however. ArrayList performs this operation automatically, hiding the details inside a class, freeing up valuable "programmer cycles" for more important tasks Another drawback with arrays is that in many cases you have to search for the element that you want. HashMap provides a way to store and look up objects using a "key" value. For example, you might want to have a list of student records, and be able to look up a student by name. HashMap gives you this functionality rrayLists Array List is a " generic", also called a "parameterized type" This means that you can declare different kinds of Array List to hold different object types. Declaring a generic in Java is done with the angle bracket notation For example, The following line of code creates a ArrayList of Strings: ArrayList stringList new ArrayList There are a couple of things to notice here. One is that an ArrayList declaration has two types (1) ArrayList itself, and (2) the kind of objects that the ArrayList will hold. Also, the right side of the statement requires both angle brackets, and parentheses (). We can think of ArrayList String as the type of object we are creating Just like any other object, to instantiate it, we call the constructor using "new" and parentheses 0. Unlike an array, we don't have to give the ArrayList an initial size. I will expand as needed. However, you can declare an initial capacity by passing a parameter to the constructor. The following creates an ArrayList of strings with an initial capacity of 100 ArrayList stringList ArrayList(100); - new Write the answers to the numbered questions (Q1...) in a file called lab7answers.txt. At the top of this file, put our name and section number. Q1) What code would you use to create an ArrayList called studentList that holds objects of type Student? To eliminate some of the redundancy of this notation, Java allows you to omit the "String" inside the angle brackets on the right hand side (called type inference), so the following is equivalent to the above statement ArrayList stringList ArrayList(100); - new Notice that the angle brackets are still required. To add an element to the list, use the method "addExplanation / Answer
Q1) What code would you use to create an ArrayList called studentList that holds object of type Student?
Answer : ArrayList<Student> studenList = new ArrayList()<>();
Q2) What code would you use to remove last element of stringList?
Answer: stringList.remove(stringList.size()-1);
Q3) What is Autoboxing?
Answer : Java compiler makes automatic conversion between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Q4) What is the wrapper class for double?
Answer: Double
Q5) What standard loop would you use to print the elements of myList, one string per line?
Answer: For Loop
Q6) What enhanced loop would you use to print the elements of myList, one string per line?
Answer: For-Each Loop
Part - 1)
//-------- Lab7a.java ----------
import java.util.ArrayList;
public class Lab7a {
public static void main(String[] args) {
ArrayList<Double> list = createSquaresList(10);
printList(list);
removeElement(list, 4);
printList(list);
swapElements(list, 2, 6);
printList(list);
double max = getMaxValue(list);
double ave = getAverage(list);
//Print max and average
System.out.println("Max:"+max+" and Average:"+ ave);
int idx1 = linearSearch(list, 4);
int idx2 = linearSearch(list, 75);
// Print two indices
System.out.println("Element 4 found at index:"+idx1);
System.out.println("Element 75 found at index:"+idx2);
}
public static ArrayList<Double> createSquaresList(int n) {
// create arraylist with squares of n numbers, 0 to n-1
ArrayList<Double> list = new ArrayList<Double>();
for(int i=1;i<n;i++) {
list.add((double)i*i);
}
return list;
}
public static double getMaxValue(ArrayList<Double> list) {
double max = list.get(0);
for(int i=1;i<list.size();i++) {
if(max < list.get(i)) {
max = list.get(i);
}
}
return max;
}
public static double getAverage(ArrayList<Double> list) {
double ave = 0.0;
for(Double val : list) {
ave = ave + val;
}
ave = ave / list.size();
return ave;
}
public static void removeElement(ArrayList<Double> list, int index) {
// remove the specified element
list.remove(index);
}
public static void swapElements(ArrayList<Double> list, int a, int b) {
// swap elements a and b of the list.
double temp = list.get(a);
list.set(a, list.get(b));
list.set(b, temp);
}
public static int linearSearch(ArrayList<Double> list, double val) {
// use linear search to find index of a particular value.
// Return index or -1 if value not found
// do not use list.indexOf(val)
int index = -1;
for(int i=0;i<list.size();i++) {
if(list.get(i) == val) {
index = i;
break;
}
}
return index;
}
public static void printList(ArrayList<Double> list) {
// Print out numbers of list on one line, comma separated
StringBuffer sb = new StringBuffer();
for(int i=0; i< list.size();i++) {
sb.append(list.get(i));
if(i < list.size()-1) {
sb.append(",");
}
}
System.out.println(sb.toString());
}
}
Part 2) For part 2 you run this program and copy output from console and paste it in Lab7aout.txt
Q7) Suppose that your program has HashMap called plats with keys that are Strings and values that are Integers.
What code would you use to print the value associated with the string "grass"?
Answer : plants.get("grass");
Part 3)
//------ Lab7b.java -------------
public class Lab7b {
public static void main(String[] args) {
// create new HashMap called "songStars"
HashMap<String, Integer> songStars = new HashMap<String, Integer>();
// Yes, you should listen to all on Youtube.
songStars.put("The ballad of Bilbo Baggins", 5);
songStars.put("TA still more glorious dawn", 4);
songStars.put("TA finite simple group of order two", 4);
songStars.put("Code monkey", 4);
songStars.put("Fish heads", 2);
songStars.put("I'll form the head", 3);
songStars.put("Honeybee", 5);
songStars.put("Silver apples of the moon", 4);
// Get the number of stars for "Code monkey", and print the # of stars
int stars = songStars.get("Code monkey");
System.out.println(" # of stars for "Codemonkey""+stars);
// remove the song "Honeybee"
songStars.remove("Honeybee");
// Determine if "Honeybee" is still in the table.
// If it is in table, print "Honeybee still in table".
// Otherwise, print "Successfully removed Honeybee".
if(songStars.containsKey("Honeybee")) {
System.out.println("Honeybee still in table");
} else {
System.out.println("Successfully removed Honeybee");
}
}
}
Part 4) For this part copy code in your editor, compile and run.
Part 5) Your action needed.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.