Advance Java Practical Journal
ISBN 9788119221226

Highlights

Notes

  

Chapter 2: Practical on List Interface

Practical 2.1

Write a Java program to create List containing list of items

of type String and use for-each loop to print the items of the list

import java.util.ArrayList;

import java.util.List;

/* Practical 2-1

* Author: Vikram

*

* Write a Java program to create List containing list of items

* of type String and use for-each loop to print the items of the

* list.

*/

public class ListInterfaceExample1 {

public static void main(String[] args) {

// TODO Auto-generated method stub List<String> mylist=new ArrayList<String>(); mylist.add(“Prakash”);

mylist.add(“Suresh”); mylist.add(“Ramesh”); mylist.add(“Jayesh”);

for(String item: mylist) {System.out.println(item);

}

}

}

Output

Prakash Suresh Ramesh Jayesh

Practical 2.2

Write a Java program to create List containing list of items and use List Iterator interface to print items present in the list. Also print the list in reverse/ backward direction.

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

/*

* Write a Java program to create List containing list of items

* and use List Iterator interface to print items present in the

* list. Also print the list in reverse/ backward direction.

*/

public class ListInterfaceRevFor {

public static void main(String[] args) {

// TODO Auto-generated method stub

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

//Generating list of 10 numbers

for(int i=1;i<=10;i++) numberlist.add(i);

// printing the list using iterator Iterator<Integer> itr=numberlist.iterator(); while(itr.hasNext())

{

System.out.println(itr.next());

}

// printing the list using iterator in reverse order System.out.println(“Reverse order”); Collections.reverse(numberlist);

Iterator<Integer> itr2=numberlist.iterator();

while(itr2.hasNext())

{

System.out.println(itr2.next());

}

}

}

Output

1

2

3

4

5

6

7

8

9

10

Reverse order 10

9

8

7

6

5

4

3

2

1