Ça me plaisait toujours pas trop, vu que le type est vérifié aux entrées de fonctions, donc encore une autre version :(
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collection;importjava.util.Iterator;importjava.util.LinkedList;importjava.util.List;publicclassClassA{// here, you just say what types are acceptedprivateclassClassB<IextendsInteger,SextendsString>implementsIterable{// it's a bit more wrapping, but for the funprivateCollectionc;publicClassB(Collectionc){// we could do better, just a bit of safety hereif(!c.isEmpty())c.clear();this.c=c;}privatevoidadd(Object...params)throwsException{this.c.addAll(checkIn(params));}privateCollection<Object>checkIn(Object...params)throwsException{// here we can do a bunch of checks. Choose your own. It's just the entry gateif(params.length==0)thrownewException("You shall not pass!");returnArrays.asList(params);}publicvoidaddInt(Ii)throwsException{add(i);}publicvoidaddManyInts(I...i)throwsException{add(i);}publicvoidaddString(Ss)throwsException{add(s);}publicvoidaddManyStrings(S...s)throwsException{add(s);}privateintgetNumerOfBidules(Classc){intr=0;for(Objecto:this.c){if(c.isInstance(o))r++;}returnr;}publicCollection<Object>filter(Classc){List<Object>r=newArrayList<Object>();for(Objecto:this.c){if(c.isInstance(o))r.add(o);}returnr;}publicIteratoriterator(){returnc.iterator();}}publicstaticvoidmain(String[]args)throwsException{ClassAa=newClassA();a.doThings();}publicvoiddoThings()throwsException{ClassB<Integer,String>maListeDeBidules=newClassB<>(newLinkedList());maListeDeBidules.addInt(1);// okmaListeDeBidules.addString("deux");// okmaListeDeBidules.addManyInts(3,4,5,6,7,8);// okmaListeDeBidules.addManyStrings("neuf","dix","onze","douze","treize","quatorze");// okinti=0;for(Objecto:maListeDeBidules){System.out.println("mon bidule "+(i+1)+" : "+o);i++;}System.out.println("La moyenne dans ma liste de bidules est de : "+this.getMean(maListeDeBidules));// here we go!ClassB<Integer,String>maListeDeBidules2=newClassB<>(newArrayList());for(i=0;i<10000000;i++)maListeDeBidules2.addInt(i);}publicdoublegetMean(ClassB<Integer,String>b)throwsException{Class<Number>c=Number.class;intn=b.getNumerOfBidules(c);if(n==0)thrownewException("Maybe you want numbers...");doublemean=0;for(Objectv:b.filter(c)){mean+=((Number)v).doubleValue()/n;}returnmean;}}
[^] # Re: Typage
Posté par _kaos_ . En réponse au message débutant java : opérations de base sur les listes. Évalué à 2.
Salut,
Ça me plaisait toujours pas trop, vu que le type est vérifié aux entrées de fonctions, donc encore une autre version :(
Matricule 23415