How can I add elements into the ArrayList in reverse order?
Working fine in forward order!
package com.codegym.task.task07.task0710;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
To the top of the list
1. Create a list of strings in the main method.
2. Add 10 strings to it from the keyboard, but only add them to the beginning of the list, not the end.
3. Use a loop to display the contents, each value on a new line.
*/
public class Solution {
public static void main(String[] args) throws Exception {
//write your code here
String ind_con = ""; //individual_content
ArrayList<String> con = new ArrayList<String>(); //1 --- con <- content --- () <- means size not set to any arbitary value!
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < 10; i++) {
ind_con = reader.readLine(); //2
con.add((9 - i), ind_con); //2 put individual_content into the list of contents
}
/*
Solution 1:
for(String print: con)
System.out.println(print); //print out each individual_content
//no need of 'i' variable as it wasn't declared in the loop body, so each element is always printed as usual!
*/
/*
Solution 2:
*/
for(int i = 0; i < 10; i++)
System.out.println(con.get(i)); //.get(i) will give each individual String from index(i) 0 to 9
}
}