Is there a way to "combine" these loops, or a way to only write them once but still get each list to print independently?
public static void printAnimals(String listType) {
if (listType.equals("dog") {
for (Dog obj: dogList) {
System.out.println("elements"); // example output
}
}
if (listType.equals("cat") {
for (Cat obj: catList) {
System.out.println("elements") // example output
}
}
In my actual code, there is a 3rd option "available" that prints a list of available dogs and available cats. So there, too, I have 2 identical loops that go through each list and prints only dogs or cats that are available. They're already written, so if it is the only way, it's the only way. I simply have a vague suspicion that there is probably a more efficient way.
if (listType.equals("available") {
for (Dog obj: dogList) {
if (dog.getStatus().equals("unreserved") {
System.out.println("unreserved dogs")
}
}
for (Cat obj: catList) {
if (cat.getStatus().equals ("unreserved") {
System.out.println("unreserved cats")
}
}
}
CodePudding user response:
You must use a single variable to be a reference for your list of animals and depending of kind of listype this variable is ponting to one list or another.
It's the most basic way to solve your issue.
public static void printAnimals(String listType) {
var myList = listType.equals("dog") ? dogList : catList;
for (Obj obj: myList) {
System.out.println("elements"); // example output
}
}
There is also another way that is a better solution:
public static void printDogs() {
printAnimals(dogList);
}
public static void printCats() {
printAnimals(catList);
}
private static void printAnimals(List animals) {
for (Animal obj: animals) {
System.out.println("elements"); // example output
}
}
You must to ensure that Dogs and Cats extends a commnon Animal class.
CodePudding user response:
By using the OOP
principles, that here it is known as Inheritance
, you can do something like this:
public class Animal {
public void printAnimals(List<Animal> list) {
System.out.println("do anything"); // sample output
}
}
public class Dog extends Animal {
@Override
public void printAnimals(List<Animal> list) {
System.out.println("print dogs"); // dogs output
}
}
public class Cat extends Animal {
@Override
public void printAnimals(List<Animal> list) {
System.out.println("print cats"); // cats output
}
}