Java tutorial
package org.michelcity2000.city.stock; /* * ResourceHeap.java * Copyright (C) Remi Even 2014-2015 * * This file is part of MichelCity2000. * * MichelCity2000 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MichelCity2000 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MichelCity2000. If not, see <http://www.gnu.org/licenses/>. * * Additional permission under GNU GPL version 3 section 7 * If you modify this Program, or any covered work, by linking or combining * it with JSON-java (or a modified version of that library), containing * parts covered by the terms of JSON license, the licensors * of this Program grant you additional permission to convey the resulting * work. */ import java.util.ArrayList; import java.util.Collections; import org.json.JSONArray; @SuppressWarnings("serial") public class ResourceHeap extends ArrayList<Resource> { public ResourceHeap(Resource res) { this.add(res); } public ResourceHeap(JSONArray jsonResources) { int ResourcesNumber = jsonResources.length(); for (int i = 0; i < ResourcesNumber; i++) this.add(Resource.parseResource(jsonResources.getString(i))); } public ResourceHeap() { super(); } /** * Add a resource to the Arraylist. Do not use add (we want all the resource of the same type together) * @param resource the resource to add */ public void addResource(Resource resource) { if (resource.getQuantity() == 0) return; int i = 0; while ((i < this.size()) && !(this.get(i).getName().equals(resource.getName()))) i++; // if there aren't any resource with the appropriate type in the list if (i == this.size()) this.add(new Resource(resource.getName(), resource.getQuantity())); else this.get(i).add(resource.getQuantity()); } public void sort() { Collections.sort(this); } public int totalAmount() { int n = 0; for (Resource r : this) n += r.getQuantity(); return n; } public ResourceHeap clone() { ResourceHeap res = new ResourceHeap(); for (Resource r : this) res.add(r.clone()); return res; } }