How to write an immutable class using Arraylist? Can you give me an example 2. C
ID: 3710908 • Letter: H
Question
How to write an immutable class using Arraylist? Can you give me an example
2. Create a class to serve as a crime data type. To do this, create an immutable class (a class without "setters", only private fields, constructors and "getters") to hold one campus crime record for one year, i. e. to hold one line of data from the file as individual data elements (not as a single string).
(a) Right click on the package "pa7_your-id" and select New, Java Class. Name the class appropriately. This class will be referred to in this document as the "crime class"
(b) Suggestion: Include methods to return summary information. Example, a method to return total students and another to return total crimes.
2. Create a class to serve as a crime data type. To do this, create an immutable class (a class without "setters", only private fields, constructors and "getters") to hold one campus crime record for one year, i. e. to hold one line of data from the file as individual data elements (not as a single string). (a) Right click on the package "pa7_your-id" and select New, Java Class. Name the class appropriately. This class will be referred to in this document as the "crime class" (b) Suggestion: Include methods to return summary information. Example, a method to return total students and another to return total crimes.Explanation / Answer
import java.util.List;
import java.util.ArrayList;
public final class CrimeClass {
private final List<String> strings = new ArrayList<String>();
public CrimeClass() {
strings.add("string 1");
strings.add("string 2");
}
public List<String> getStrings() {
List<String> newStrings = new ArrayList<String>();
strings.forEach(s -> newStrings.add(s));
return newStrings;
}
public static void main(String[] args) {
CrimeClass in = new CrimeClass();
System.out.println(in.getStrings());
in.getStrings().add("string 3");
System.out.println(in.getStrings());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.