How to Use Java List Function

The java.util.List interface is a subtype of the Java.util.Collection interface. It represents an ordered list of objects, mean you can access the elements of a List in a specific order, and by an index too. You can also add the same element more than once to a List.

Source Code 


import java.util.*;
import java.util.Scanner;
public class ListFunction {
   
      static  List<Integer> integer_list = new ArrayList<Integer>();
      public static void main(String[] args) {
      Scanner input=new Scanner(System.in);
        boolean y=true;
        System.out.println("**** List in Java ******* ");
        do{  
         System.out.println(" 1 : Insert ");
         System.out.println(" 2 : Search ");
         System.out.println(" Choice : ");
         int choice=input.nextInt();
         switch(choice)
         {
            case 1:
                insert();
                break;
            case 2:
                search();
                break;
            default:
                System.out.println("Invalid Input");
                break;
        }
        System.out.println("Want Again (y/n) ? ");
        String x=input.next();
        char ch=x.charAt(0);
        if( ch=='n')
            y=false;
    }
    while(y!=false);

    }
    public static void insert()
    {
           
       Scanner insert=new Scanner(System.in);
        
        boolean y=true;
       do{
            System.out.println("Enter Number : ");
            int num=insert.nextInt();
            if(num==0)
                System.out.println("Enter Number Greater Than Zero ! ");
            else
                integer_list.add(num);
            System.out.println("Insert Again (y/n) ?");
            String next=insert.next();
            char ch=next.charAt(0);
            if( ch=='n')
                y=false;
         }
       while(y!=false);
   }
     public static void search()
     {
       System.out.println("Enter Number for Search = ");
       Scanner search=new Scanner(System.in);
       int num=search.nextInt();
       for(int i=0;i<integer_list.size();i++){
           if(integer_list.get(i)==num)
                System.out.println(num+" Found in Index : "+i);
       }
       
       if(integer_list.lastIndexOf(num)==-1)
               System.out.println(num+" Not Present :( ");
     }

}

Output of the Program 

Java List
Java List Collection

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. i think
    Array List can stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead

    ReplyDelete