User Tools

Site Tools


sysrep:java

Compléments Java

Readline : Pour lire une chaîne de caractères sur la ligne de commande, il faut taper un truc comme ça :

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
  String msg = in.readLine();
} catch(IOException e) { /* ... */ }

StringTokenizer : Pour décomposer une chaîne de caractères en mots (les tokens) :

StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) System.out.println(st.nextToken());

Affiche ici :

this
is
a
test

HashMap and Generics : Voici un petit exemple d'utilisation des Generics avec les HashMap.

HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "Ian");
map.put(2, "Scott");
String name = map.get(2)
 
for (Integer key : map.keySet())  
  System.out.println("key = " + key + ", value = " + map.get(key));

Intrinsic Locks and Synchronization : En java chaque objet dispose d'un verrou intrinséque (mutex), qui est utile pour synchroniser l'accès au champs d'un objet via de multiple threads. Soit on déclare une méthode comme “synchronized”, l'exclusion porte alors sur tout la méthode :

class FooBar {
  synchronized void foo() { ...}
  synchronized void bar() { ...}
}

Soit on déclare un bloc de code “synchronized”, en précisant explicitement l'objet qui fournit le lock.

Object lock = new Object;
synchronized(lock) { 
  ...
  ...
}
sysrep/java.txt · Last modified: 2024/03/18 15:06 by 127.0.0.1