Exemples: Utilisation du collections

On regarde un implantation simple des Collections fait par Watt et Brown et modifié par Guy Lapalme. Les fichiers sont trouvés dans CollectionsSimplifiees.

Voir aussi le PDF ShowCollections.pdf. Il y a un démo applet avec source.

Exemples


ListExample.java
import java.util.*;
import java.io.*;

public class ListExample {
    public static void main(String args[]) {
        List l1 = new ArrayList();

	try {
	    String str;
	    String [] words;
	    BufferedReader in = new BufferedReader(new FileReader(args[0]));
            while ((str = in.readLine()) != null) {
		words = str.split(" ");
		l1.addAll(Arrays.asList(words));
	    }


        } catch (IOException e) {
            System.err.println(e);
            return;
        }
	

	List l2 = new ArrayList(l1);
	//l2.addAll(l1);	

	
	String s = args[0];

	List l3 = l1.subList(0,4);

	System.out.println("l1: " + l1);
	System.out.println("l2: " +l2);
	System.out.println("l3: " + l3);

	Collections.shuffle(l1,new Random());

	System.out.println("l1 apres shuffle: " + l1);
	System.out.println("l2 apres shuffle: " + l2);
	System.out.println("l3 apres shuffle: " + l3);




    }
}

MapExample.java
Vous pouvez appeler MapExample avec le fichier great_beagle.txt qui contient deux vieux livres en anglais.
import java.util.*;
import java.io.*;
public class MapExample {
    public static void main(String args[]) {
        Map m = new TreeMap();

	try {
	    String str;
	    String [] words;
	    BufferedReader in = new BufferedReader(new FileReader(args[0]));
            while ((str = in.readLine()) != null) {
		words = str.split(" ");
		for (int i=0;i<words.length;i++) {
		    if (m.containsKey(words[i])) {
			m.put(words[i],new Integer((Integer)m.get(words[i])+1));
		    } else {
			m.put(words[i],new Integer(1));
		    }
		}
	    }
        } catch (IOException e) {
            System.err.println(e);
            return;
        }
	    
	System.out.println("Map: " + m);
    }
}

Last modified: Mon Nov 28 13:42:42 EST 2005 par Douglas Eck [douglas D0T eck AT umontreal D0T ca]