1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
/* Search an element of Java Vector from specific index Example This Java Example shows how to search an element of java Vector from specific index using indexOf and lastIndexOf methods. */ import java.util.Vector; public class SearchAnElementFromSpecificIndexVectorExample { public static void main(String[] args) { //create a Vector object Vector v = new Vector(); //Add elements to Vector v.add("1"); v.add("2"); v.add("3"); v.add("4"); v.add("5"); v.add("1"); v.add("2"); /* To search an index of specified element in Vector from specified index use int indexOf(Object element, int startIndex) method. This method returns the index of the first occurence of the specified element after startIndex in Vector. It returns -1 if not found. */ int index = v.indexOf("1",4); if(index == -1) System.out.println("Vector does not contain 1 after index # 4"); else System.out.println("Vector contains 1 after index # 4 at index #" + index); /* To get last index of specified element after specified index in Vector use int lastIndexOf(Object element, int startIndex) method. This method returns index of the last occurrence of the specified element after startIndex in Vector. It returns -1 if not found. */ int lastIndex = v.lastIndexOf("2" , 5); if(lastIndex == -1) System.out.println("Vector does not contain 2 after index # 5"); else System.out.println("Last occurrence of 2 after index # 5 in Vector is at index #" + lastIndex); } } /* Output would be Vector contains 1 after index # 4 at index #5 Last occurrence of 2 after index # 5 in Vector is at index #1 */ |
Add Comment