Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class SimpleCollection {
- private String name;
- private ArrayList<String> elements;
- public SimpleCollection(String name) {
- this.name = name;
- this.elements = new ArrayList<>();
- }
- public void add(String element) {
- this.elements.add(element);
- }
- public ArrayList<String> getElements() {
- return this.elements;
- }
- public String toString(){
- String printOutput = "";
- if(this.elements.isEmpty()){
- return "The collection " + this.name + " is empty.";
- }
- // adding all elements to the printOutput String.
- for(int i =0; i< this.elements.size(); i++){
- printOutput+= this.elements.get(i) + "\n";
- }
- // if only one element then just print it as a singular sentence ,
- // else print elements as plural.
- if(this.elements.size() == 1){
- return "The collection " + this.name + " has " + this.elements.size() + " element:" + "\n" + printOutput;
- }
- return "The collection " + this.name + " has " + this.elements.size() + " elements:" + "\n" + printOutput;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement