Tipuri de date și excepții în Java
Jim White
Java Developer
List, sub-interfață a CollectionListArrayList - listă ordonată, indexată (similar cu array-urile), redimensionabilă
LinkedList - obiecte conectate prin legături la obiectele anterioare și următoare.
new și folosiți generics pentru a specifica tipul de conținut.add(object).get(index)ArrayList utilizează index de la zero.set(index, object).remove(index).clear().size()import java.util.ArrayList; ... ArrayList<String> animals = new ArrayList<String>();animals.add("horse"); animals.add("cow"); animals.add("horse"); // Duplicates allowedString c = animals.get(1); // c="cow" animals.set(1, "chicken");// Removes the first horse animals.remove(0); // Removes all objects animals.clear();animals.size();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(5));
list.add(6); // 6 is automatically wrapped by Integer then added
Object ca tip parametrizatArrayList<Object> list = new ArrayList<Object>(); // Allow any object
list.add(new Integer(5)); // Add an Integer
list.add(6); // Add an Integer using autoboxing
list.add("Hello"); // Add a String
ListArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
for (String animal : animals) { // fore-each to loop through all in the ArrayList
System.out.println(animal);
}
horse
cow
chicken
List (ex.: ArrayList) poate fi afișat cu printlnArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
System.out.println(animals); // Display all the elements in the ArrayList
ArrayList<Object> list = new ArrayList<Object>();
list.add(5);
list.add("Hello");
System.out.println(list); // Display all the elements in the ArrayList
[horse, cow, chicken]
[5, Hello]
LinkedList se construiesc similar cu instanțele ArrayListLinkedList au aceleași metode ca ArrayListimport java.util.LinkedList;
...
LinkedList<String> cars // Create a new ...
= new LinkedList<String>(); // ... LinkedList
cars.add("Ford"); // Add an object to the list
cars.add("Mercedes");
String c = cars.get(1);
cars.set(1, "Toyota"); // Replace an object
System.out.println(cars); // Display the list
cars.remove(0); // Remove an object
cars.clear(); // Remove all objects
cars.size(); // Get the list length
[Ford, Toyota]
addFirst() adaugă la începutul listeiaddLast() adaugă la sfârșitul listeiremoveFirst() elimină de la începutremoveLast() elimină de la sfârșitcars.addFirst("Fiat"); // Add to the beginning
cars.addLast("BMW"); // Add the the end
cars.removeFirst(); // Remove the first object
cars.removeLast(); // Remove the last object
ArrayList și LinkedList par similareListArrayList și LinkedList (sau orice List) sunt identiceList depinde de utilizareArrayList:list.get(11))
LinkedList:list.get(11))
Tipuri de date și excepții în Java