Sintassi per le collezioni non
generiche :
List
myList = new
ArrayList();
myList.add("stringa");
myList.add(2);
String
s1 = (String) myList.get(0);
int s2 = (int) myList.get(0);
La
lista myList non è generica.
Quindi
ci possiamo mettere oggetti di tipi diversi (non type-safe), come una String o
un int. Quando si recuperano gli oggetti siccome il compilatore non sa di che
tipo sono gli oggetti così recuperati vanno castati.
L’ultima
riga evidenzia il problema della collezioni non generiche; infatti il
compilatore permette di scrivere la linea di codice ma questa a run time
provoca una eccezione, infatti stiamo cercando di castare ad intero un elemento
che in realtà è una stringa:
Exception
in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Sintassi
per le collezioni generiche :
List<String> myList = new ArrayList();
myList.add("stringa");
* myList.add(2);
String
s1 = myList.get(0);
* int s2 = (int) myList.get(0);
In questo caso il
compilatore segnala subito un errore se proviamo ad inserire un elemento intero
dentro la collezione generica. Ancora più importante il compilatore segnala un
errore se si cerca di recuperare un intero da una collezione di Stringhe.
Questo rende il codice più robusto.
Hi and I just passed 1z0 804 on this october,I want to share 1 of question that I still remember. Please put this on our blog. Btw thanks for build this awesome blog I passed because of your blog cheers :D
RispondiEliminapublic class TestInteger {
public static void main(String[] args) {
Integer i3= new Integer(5);
i3 = 777;
int psn = 777;
Integer i4= new Integer(psn);
System.out.println(i3.equals(i4));
}
}
the result is ?
A.true
B.false
C.compilation failed
answer :
A.true
Questo commento è stato eliminato dall'autore.
RispondiEliminaQuesto commento è stato eliminato dall'autore.
EliminaHere another one :
RispondiEliminaWhich to proper way to use java readpassword? <-- i dont remember the exactly question
a. char[] password = cnsl.readPassword();
b. String username = "root";
char[] password = cnsl.readPassword("lalala %1$s", username);
c. String username = "root";
String[] password = cnsl.readPassword("lalala %1$s", username);
d. String[] password = cnsl.readPassword();
the answer is A and B
Which the properway to declare Arraylist choose 3?
RispondiEliminaa.ArrayList arrayList = new ArrayList();
b.List arrayList4 = new ArrayList<>();
c.ArrayList<> arrayList5 = new ArrayList<>();
d.ArrayList<> arrayList6 = new ArrayList();
e.ArrayList<> arrayList7 = new ArrayList();
f.ArrayList arrayList8 = new ArrayList();
answer ABF
Hello i will add the question that i remembered below,
RispondiEliminaenum Alphabet{
C,D,G,B,A}
which is the best answer to prints "4" ?
a. Alphabet.values();
b. Alphabet.ordinal();
c. Alphabet.indexOf("A");
d. Alphabet.valueOf("A");
e. Alphabet.valueOf("A").ordinal();
Questo commento è stato eliminato dall'autore.
RispondiElimina