1 Collections
1 Collections
Collections(1/2): Lists.
BoxPrinter<Integer> value1 =
new BoxPrinter<Integer>(new Integer(10));
System.out.println(value1);
BoxPrinter<String> value2 =
new BoxPrinter<String>("Hello world");
System.out.println(value2);
Notes for example
You are declaring val of the generic type—the actual type will be
specified later when you use BoxPrinter.
In main() , you declare a variable of type BoxPrinter for an
Integer like this:
BoxPrinter<Integer> value1
boolean hasNext();
E next();
Let’s see:
List<String> myArrList = new ArrayList<String>();
Starting with Java version 7, you can omit the object type on the
right side of the equal sign and create an ArrayList as follows:
Using ListIterator:
ListIterator<String> iterator =
myArrList.listIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Modifying the elements
of an ArrayList
List<String> myArrList = new ArrayList<>();
myArrList.add("One");
myArrList.add("Two");
myArrList.add("Three");
myArrList.set(1, "One and Half");
for (String element:myArrList) {
System.out.println(element);
}
Deleting the elements
of an ArrayList
ArrayList<String> myArrList = new ArrayList<>();
String s1 = "One";
String s2 = "Two";
String s3 = "Three";
String s4 = "Four";
myArrList.add(s1);
myArrList.add(s2);
myArrList.add(s3);
myArrList.add(s4);
myArrList.remove(1);
for (String element:myArrList) {
System.out.println(element);
}
myArrList.remove(s3);
myArrList.remove("Four");
System.out.println();
for (String element : myArrList) {
System.out.println(element);
}
Example
Other methods of ArrayList
Adding multiple elements to an ArrayList
You can add multiple elements to an ArrayList from another
ArrayList or any other class that’s a subclass of Collection by
using the following overloaded versions of method addAll: