Upload files to "DEV.3.2/cours"
This commit is contained in:
80
DEV.3.2/cours/1.Généricité.md
Normal file
80
DEV.3.2/cours/1.Généricité.md
Normal file
@@ -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> T troisieme(T[] tab) {
|
||||||
|
return tab[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String argument = troisieme(args);
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
public class Paire<E> {
|
||||||
|
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<Integer> p;
|
||||||
|
p = new Paire<Integer>(12, 7);
|
||||||
|
System.out.println(p.get(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
//
|
||||||
|
public static void <T extends JComponent> ajouterComposants(LinkedList<T> liste, Container conteneur) {
|
||||||
|
conteneur.setLayout(new GridLayout(liste.size(), 1));
|
||||||
|
for(JComponent composant : liste) {
|
||||||
|
conteneur.add(composant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static void ajouterComposants(LinkedList<? extends JComponent> liste, Container conteneur) {
|
||||||
|
conteneur.setLayout(new GridLayout(liste.size(), 1));
|
||||||
|
for(JComponent composant : liste) {
|
||||||
|
conteneur.add(composant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static <T> void remplirPaire(Paire<? super T> destination, T e1, T e2) {
|
||||||
|
destination.set(0, e1);
|
||||||
|
destination.set(1, e2);
|
||||||
|
}
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user