JavaRush /Java Blog /Random EN /Generics in Java (practice)

Generics in Java (practice)

Published in the Random EN group
Create a class with a list of objects of arbitrary nature (any class). The class includes a method called PrintListwith a boolean parameter. The method displays odd or even list elements to the console, depending on the value of the parameter (true or false).
  1. Building a generic class
  2. Declare an ArrayList with a parametric type (create a list)
  3. Create a method that fills the list with data
  4. 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 Stringinstead 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 PrintListonly instead Stringit is used Integerand odd values ​​are output.
PrintList<Integer> plI = new PrintList<Integer>();
	for (int i = 0; i < 10; i++){
		plI.add(i);
	}
	plI.printList(false);
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION