diff --git a/DEV.3.2/cours/1.Généricité.md b/DEV.3.2/cours/1.Généricité.md new file mode 100644 index 0000000..19bb7fa --- /dev/null +++ b/DEV.3.2/cours/1.Généricité.md @@ -0,0 +1,80 @@ +### Cours sur la généricité en java + +```java +public static Object troisieme(Object[] tab) { + return tab[2]; +} + +public static void main(String[] args) { + String argument = (String) troisieme(args); + ... +} +``` + +```java +// La même fonction que la précédente +public static T troisieme(T[] tab) { + return tab[2]; +} + +public static void main(String[] args) { + String argument = troisieme(args); + ... +} +``` + +```java +public class Paire { + private E elementUn; + private E elementDeux; + public Paire(E e1, E e2) { + this.elementUn = e1; + this.elementDeux = e2; + } + public E get(int index) throws IndexOutOfBoundsException { + if (index == 0) { + return this.elementUn; + } else if (index == 1) { + return this.elementDeux; + } else { + throw new IndexOutOfBoundsException("La valeur "+index+" n'est pas acceptable !"); + } + } +} +``` + +```java +public class Main { + public static void main(String[] args) { + Paire p; + p = new Paire(12, 7); + System.out.println(p.get(1)); + } +} +``` + +```java +// +public static void ajouterComposants(LinkedList liste, Container conteneur) { + conteneur.setLayout(new GridLayout(liste.size(), 1)); + for(JComponent composant : liste) { + conteneur.add(composant); + } +} +``` + +```java +public static void ajouterComposants(LinkedList liste, Container conteneur) { + conteneur.setLayout(new GridLayout(liste.size(), 1)); + for(JComponent composant : liste) { + conteneur.add(composant); + } +} +``` + +```java +public static void remplirPaire(Paire destination, T e1, T e2) { + destination.set(0, e1); + destination.set(1, e2); +} +```