Typy danych i wyjątki w Javie
Jim White
Java Developer
List, podinterfejs CollectionListArrayList – zmienialny, indeksowany (jak tablice), uporządkowany zbiór obiektów
LinkedList – obiekty połączone łączami do następnego i poprzedniego obiektu.
new i użyj generyków do określenia typu zawartości.add(object).get(index)ArrayList używa indeksu od zera.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 jako typu parametryzowanegoArrayList<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 (np. ArrayList) można wyświetlić za pomocą 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 tworzy się podobnie jak instancje ArrayListLinkedList posiada te same metody co 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() dodaje na początku listyaddLast() dodaje na końcu listyremoveFirst() usuwa z początkuremoveLast() usuwa z końcacars.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 wyglądają podobnieListArrayList i LinkedList (lub dowolnej List) są takie sameList zależy od zastosowaniaArrayList:list.get(11))
LinkedList:list.get(11))
Typy danych i wyjątki w Javie