Introduction to Java
This Java program demonstrates reading and displaying integers, both in reverse and ascending order using ArrayList. Learn ArrayList basics and operations for efficient data handling.
Introduction to Java
E N D
Presentation Transcript
Introduction to Java ArrayLists
Write a program that reads 3 integers and displays them for (inti = 0; i < 3; i=i+1) { intval = in.nextInt(); System.out.println(val); }
Write a program that reads integers contained in a file and display them in reverse order • Input: 5 2 76 8 1 • Output: 1 8 76 2 5 • Observations: • Can not start displaying until we have read the last value • The last value must be displayed first • Can not forget any values
int v1, v2, … vn v1= in.nextInt(); v2= in.nextInt(); … vn=in.nextInt(); System.out.println(vn); system.out.println(vn-1); … system.out.println(v1); • Write a program that reads integers contained in a file and display them in reverse order • Will not work!! • Don’t know how many variables do we need
ArrayList • A sequence of 0 or more values under a common name • Values of common types • Values are distinguished by their position a 1 5 3 2 18 11 0 1 2 3 4 5
Operations • create new ArrayList<Type>(); Creates an ArrayList of type Type with size 0; ArrayList <Integer> a = new ArrayList<Integer>();
Operations • add (x) • Increase the size of the ArrayList by 1 • Place value x at the end of ArrayList
Operations • int size() • return the size of the ArrayList
Operations • get (i) • return the value at position i of the ArrayList • i < size();
Operations • set(i, x) • sets the value at position i of the ArrayList to x • i < size();
Write a program that reads integers contained in a file and display them in reverse order • Input: 5 2 76 8 1 • Output: 1 8 76 2 5
Write a program that reads integers contained in a file and display them in Ascending order • Input: 5 2 76 8 1 • Output: 1 2 5 8 76