On rappelle que la classe Enumeration permet de parcourir des classes contenant des collections d'objets. Pour l'utiliser, il suffit de l'implémenter !!!
package java.util; public interface Enumeration{ boolean hasMoreElements(); Object nextElement() throws NoSuchElementException; }
class EnumTab{ public static Enumeration enumerer(final Object[] objs){ class Enum implements Enumeration { private int pos = 0; public boolean hasMoreElements(){ return (pos < objs.length); } public Object nextElement() throws NoSuchElementException { if (pos >= objs.length ) throw new NoSuchElementException(); return objs[pos++]; } } return new Enum(); } }
On notera:
class ParcoursLineaire{ public static boolean parcourir(Enumeration tab, Object o){ while(tab.hasMoreElements()) if(o.equals(tab.nextElement())) return true; return false; } }
class Main{ public static void main(String[] args){ Object[] t= new Integer[10]; Vector v=new Vector(); for(int i=0; i<t.length; i++){ t[i]=new Integer(i*i); v.add(new Integer(i*i)); } if(ParcoursLineaire.parcourir(EnumTab.enumerer(t), new Integer(81))) System.out.println("OK"); if(ParcoursLineaire.parcourir(v.elements(), new Integer(81))) System.out.println("OK"); } }