Write a Java program that will create an ArrayList that holds integers. Choose 1
ID: 3576267 • Letter: W
Question
Write a Java program that will create an ArrayList that holds integers. Choose 10 integers (not already sorted) to put into the ArrayList so that after each number is added to the ArrayList it is sorted. Each number you add to the ArrayList must be placed in the correct spot using a linear search to find the right spot then add the number there. You must use the add(index, element), get(index) and size( ) methods to perform the search and then to place the element. Display the contents of the ArrayList after each number added to verify that the ArrayList is sorted each time. Next try the 2 remove methods: remove(index) and remove(element). Print out the ArrayList after each remove to verify it worked. Try each at least twice. (Data structure java)
Explanation / Answer
import java.util.*;
import java.io.*;
public class AList
{
public static void main(String ar[])
{
ArrayList<Integer> a1=new ArrayList<Integer>(10);
Scanner s=new Scanner(System.in);
int i=1,j,temp,n,ind,elem;
for(i=0;i<10;i++)
{
n=s.nextInt();
Collections.sort(a1);
a1.add(i,n);
}
Collections.sort(a1);
System.out.println("After sorting elements:");
for(i=0;i<10;i++)
System.out.print(","+a1.get(i));
System.out.println("enter index to remove:");
ind=s.nextInt();
System.out.println("enter element to remove:");
elem=s.nextInt();
a1.remove(ind);
for(i=0;i<10;i++)
{
if(elem==a1.get(i)){
a1.remove(i);
break;
}
}
for(i=0;i<a1.size();i++)
System.out.print(a1.get(i)+",");
}}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.