Create a class with a list of objects of arbitrary nature (any class). The class includes a method called
PrintList
with a boolean parameter. The method displays odd or even list elements to the console, depending on the value of the parameter (true or false).
- Building a generic class
- Declare an ArrayList with a parametric type (create a list)
- Create a method that fills the list with data
- Create a method that prints either even or odd values
public class PrintList<T> {
private ArrayList<T> list = null;
public PrintList() {
list = new ArrayList<T>();
}
public void add(T data) {
list.add(data);
}
public void printList(boolean isOdd) {
int size = list.size();
if (isOdd) {
for (int i = 1; i < size; i += 2) {
System.out.println(list.get(i).toString());
}
} else{
for (int i = 0; i < size; i += 2) {
System.out.println(list.get(i).toString());
}}}
}
I create an object of the class PrintList
, but with a concrete class String
instead of a parametric type. I'm filling out the list. It will consist of 10 lines. And now if plS.printList(true)
, then even lines will be displayed. And if plS.printList(false)
, then odd.
public static void main(String[] args) {
PrintList<String> plS = new PrintList<String>();
for (int i = 0; i < 10; i++){
plS.add("" + i);
}
plS.printList(true);
Then I create an object of the class PrintList
only instead String
it is used Integer
and odd values are output.
PrintList<Integer> plI = new PrintList<Integer>();
for (int i = 0; i < 10; i++){
plI.add(i);
}
plI.printList(false);
}
GO TO FULL VERSION