package com.example.generic;

import java.util.ArrayList;
import java.util.List;

public class GenericExample {

	public static void main(String[] args) {

		System.out.println("== Non Generic List ==");
		// non-generic list
		List list = new ArrayList();

		// add anything to list
		list.add("hello");
		list.add(true);
		list.add(123);

		// retrieval with non-generic is tedious
		// 1. check the actual datatype
		// 2. casting/convert
		// 3. access the value
		for (Object o : list) {
			if (o instanceof String) {
				System.out.println("this is a string value: " + o);
			} else if (o instanceof Integer) {
				int i = (int) o;
				System.out.println("total: " + (i * 2));
			}
		}

		// generic list
		List<String> genlist = new ArrayList<>();

		genlist.add("hello");
		genlist.add("john");
		// genlist.add(123); // error, not allowed
		// genlist.add(true); // error too

		for (String s : genlist) {
			System.out.println(s);
		}

		List<Integer> numlist = new ArrayList<>();
		numlist.add(12);
		numlist.add(40);
		numlist.add(88);
		int total = 0;
		for (int i : numlist) {
			total += i;
		}
		System.out.println("total: " + total);
	}

}
