Java List Interface
List Interface is the
subinterface of Collection.It contains methods to insert and delete elements in
index basis.It is a factory of ListIterator interface.
Commonly
used methods of List Interface:
- public
void add(int index,Object element);
- public
boolean addAll(int index,Collection c);
- public
object get(int Index position);
- public
object set(int index,Object element);
- public
object remove(int index);
- public
ListIterator listIterator();
- public
ListIterator listIterator(int i);
class Testc1
{
public static void main(String gh[])
{
ArrayList al1=new ArrayList();
al1.add("Ram");
al1.add("Shyam");
al1.add("Krishan");
List li=al1.subList(0,3);
Object o=li.get(2);
System.out.println(o);
}
}
Set method
class Testc1
{
public static void main(String gh[])
{
ArrayList al1=new ArrayList();
al1.add("Ram");
al1.add("Shyam");
al1.add("Krishan");
List li=al1.subList(0,3);
//Object o=li.get(2);
System.out.println(li.set(1,"Hari"));
System.out.println(li);
System.out.println(al1);
}
}
Java ListIterator Interface
ListIterator Interface is used
to traverse the element in backward and forward direction.
Commonly
used methods of ListIterator Interface:
- public
boolean hasNext();
- public
Object next();
- public
boolean hasPrevious();
- public
Object previous();
Example
of ListIterator Interface:
1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Amit");
7. al.add("Vijay");
8. al.add("Kumar");
9. al.add(1,"Sachin");
10.
11. System.out.println("element at 2nd position: "+al.get(2));
12.
13. ListIterator<String> itr=al.listIterator();
14.
15. System.out.println("traversing elements in forward direction...");
16. while(itr.hasNext()){
17. System.out.println(itr.next());
18. }
19.
20.
21. System.out.println("traversing elements in backward direction...");
22. while(itr.hasPrevious()){
23. System.out.println(itr.previous());
24. }
25. }
26. }
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
No comments:
Post a Comment