int totalWeight = 0; for (final Dog dog : dogs) { totalWeight += dog.getWeight(); }
public class DogValidator { /* this may extend some abstract validator */ public DogValidator() { super(); } public boolean validatedDog(Dog dog) { /* You can even modify this class to have exclusions e.g. what not to validate (and then use java reflection to invoke methods - may be too advance for what you want to do */ double weight = dog.getWeight(); if(weight > 0 && weight < 500) { return true; } else { return false; } } }
public class Lab { List<Dog> dogs; public float getAveDogWeight() { float sum = 0.0f; float ave = 0.0f; if (null != dogs && dogs.size > 0) { for (Dog dog : dogs) { if (null != dog) { sum += dog.getWeight(); } } ave = // calculate ave here } return ave; } }
List<Dog> dogs = new ArrayList<>(); dogs.add(spot); dogs.add(buddy); dogs.add(mia); int result = 0; for(Dog dog : dogs) { result += dog.getWeight(); }
Set<Dog> commonDogsJanuary = new HashSet<Dog>(dogsJanuary); commonDogsJanuary.retainAll(dogsFebruary); Set<Dog> commonDogsFebruary = new HashSet<Dog>(dogsFebruary); commonDogsFebruary.retainAll(dogsJanuary); for (Dog januaryDog : commonDogsJanuary) { int januaryWeight = januaryDog.getWeight(); for (Dog februaryDog : commonDogsFebruary) { if (januaryDog.equals(februaryDog) && januaryWeight > februaryDog.getWeight()) { // Do whatever } }
List<Dog> dogs = new ArrayList<>(); for (Animal animal : mainList) if (animal instanceof Dog) dogs.add((Dog)animal); double min = dogs.get(0).getWeight(); double max = dogs.get(0).getWeight(); double sum = 0; for (Dog dog : dogs) { min = Math.min(min, dog.getWeight()); max = Math.max(max, dog.getWeight()); sum += dog.getWeight(); } System.out.format("min = %i, max = %i, average = %f%n", min, max, sum * 1.0 / dogs.size()); // or by implementing comparator Comparator <Dog> dogComparator = new Comparator<>() { public int compare (Dog dog1, Dog dog2) { return Double.compare(dog1.getWeight(), dog2.getWeight()); } }; double min = Collections.min(dogs, dogComparator).getWeight(); double max = Collections.max(dogs, dogComparator).getWeight();
Dog dog = new Dog(); dog.setWeight(45); System.out.println(dog.getWeight());
@Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + (getColor() != null ? getColor().hashCode() : 0); result = 31 * result + getWeight(); result = 31 * result + (int) (getLengthInCm() ^ (getLengthInCm() >>> 32)); result = 31 * result + (int) (getHeight() ^ (getHeight() >>> 32)); result = 31 * result + (getSex() != null ? getSex().hashCode() : 0); result = 31 * result + (isNeutered() ? 1 : 0); return result; }