Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Iterator;
- public class Pacote<E> implements Iterable<E>, Cloneable {
- public static final int NUM_MAX_ITEMS = 3;
- private ArrayList<E> pacote;
- private double capcidade;
- private double capUsada;
- public Pacote(double capcidade) {
- pacote = new ArrayList<>();
- this.capcidade = capcidade;
- this.capUsada= 0.0;
- }
- public double obtemCapacidadeOcupada() {
- return this.capUsada;
- }
- public int obtemNumItems() {
- return this.pacote.size();
- }
- public boolean estaCheio() {
- return obtemNumItems() == NUM_MAX_ITEMS;
- }
- public boolean cabe(double tamanho) {
- return (tamanho + capUsada <= capcidade) && !estaCheio();
- }
- public boolean empacota(E item, double dimensaoDoItem){
- boolean emp = true;
- if(cabe(dimensaoDoItem)){
- this.pacote.add(item);
- this.capUsada += dimensaoDoItem;
- }
- else {
- emp = false;
- }
- return emp;
- }
- public String toString(){
- StringBuilder sb = new StringBuilder();
- if(this.pacote.isEmpty()) {
- sb.append("[]");
- }else {
- sb.append("[");
- for(int i = 0; i < this.pacote.size(); i++) {
- sb.append(this.pacote.get(i).toString());
- sb.append(", ");
- }
- sb.deleteCharAt(sb.length()-1);
- sb.deleteCharAt(sb.length()-1);
- sb.append("]");
- }
- return sb.toString();
- }
- public Iterator<E> iterator() {
- //Deve implementar um iterador em vez de delegar num ja existente de um dos atributos
- //(esse apenas serve parque deve usar para confirmar resultados)
- return new Iterador();
- }
- public Pacote<E> clone () {
- Pacote<E> copia = new Pacote<E>(this.capcidade);
- Iterator<E> it = this.iterator();
- int i = 0;
- while(it.hasNext() && i < this.pacote.size()) {
- copia.pacote.add(it.next());
- i++;
- }
- copia.capUsada = this.capUsada;
- return copia;
- }
- @Override
- public boolean equals(Object obj) {
- boolean b = true;
- Pacote<E> a = (Pacote <E>) obj;
- if(a.capcidade != this.capcidade) {
- b = false;
- }else if(a.capUsada != this.capUsada) {
- b = false;
- }else {
- Iterator<E> it = this.iterator();
- int i = 0;
- while(it.hasNext() && i < this.pacote.size()) {
- if(!a.pacote.get(i).equals(this.pacote.get(i))){
- b = false;
- }
- i++;
- }
- }
- return b;
- }
- private class Iterador implements Iterator<E>{
- private int indice;
- private Iterador(){
- this.indice = 0;
- }
- @Override
- public boolean hasNext() {
- return this.indice < pacote.size();
- }
- @Override
- public E next() {
- if(hasNext()) {
- return pacote.get(indice++);
- }else {
- return null;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement