Datové typy a výjimky v Javě
Jim White
Java Developer
List, podrozhraní CollectionListArrayList – měnitelný, indexovaný (jako pole), uspořádaný seznam objektů
LinkedList – objekty propojené odkazy na předchozí a následující objekt
new a generiky určíme typ obsahu.add(object).get(index)ArrayList používá index začínající od nuly.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
ObjectArrayList<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
List použijte syntaxi „for each"ArrayList<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 (např. ArrayList) lze zobrazit 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 se vytváří stejně jako instance ArrayListLinkedList má stejné metody jako 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() přidá na začátek seznamuaddLast() přidá na konec seznamuremoveFirst() odebere ze začátkuremoveLast() odebere z koncecars.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 a LinkedList vypadají stejněListArrayList a LinkedList (nebo jakémkoli List) jsou stejnéList závisí na použitíArrayList:list.get(11))
LinkedList:list.get(11))
Datové typy a výjimky v Javě