Home » Java » ArrayList input java

ArrayList input java

Posted by: admin December 28, 2021 Leave a comment


Im looking at the problem:

Write a program which reads a sequence of integers and displays them in ascending order.

Im creating an ArrayList (which I am new to) and I want to populate with integers input from the command line. With an array I could use a for loop with

 for (int i =0; i < array.length; i++) {
      array[i] = scanner.nextInt();

but with an ArrayList of unbounded size Im not sure how to process the input?


class SortNumbers {

public static void main(String[] args) {

List numbers = new ArrayList();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter some numbers.");

while (scanner.hasNextInt()) {
int i = scanner.nextInt();

The idea with using ArrayList is to avoid the deterministic iteration counts. Try something like this:

ArrayList<Integer> mylist = new ArrayList<Integer>();
while (sc.hasNextInt()) {
    int i = sc.nextInt();


I’d rather iterate over scanner and just add to a list:

List<Integer> list = new ArrayList<Integer>();

then sort it.


You need to use ArrayList add method



You don’t need to do for loop while using arraylist. As you add content, list size will increase automatically.


First if you have an ArrayList, you would not use [] to access/set the elements. That’s for arrays, which is different from an ArrayList. You would use the add method,

Second, you need to sort the ArrayList. Check out Collections.sort in the API.

Finally, to iterate over a List, there are many constructs available. One of the most common is..

List<Integer> numbers = new ArrayList<Number>();


for (Integer number : numbers) {


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

public class sortArrayList {

    public static void main(string args[]) {
        List<Integer> arrList = new ArrayList<Integer>();
        while (scanner.hasNextIint()) {


It is not that hard.
Since you are using Array List, it is very easy!

import java.util.*;
class Arr{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);//initializing scanner class
String cont="";//String to check whether the user wants to input anymore numbers or not
List<Double> n=new ArrayList<Double>();//List that will store our numbers
while(!(cont.equals("no"))){//taking continuous input

        System.out.println("Enter number:");

        System.out.println("Do you want to continue?(type 'yes'/'no')");
Collections.sort(n);//sorts your ArrayList
System.out.println("Sorted list:");
for (Double value : n) {//displaying sorted list
        System.out.println( value);