List integer example in java
ArrayList int, Integer ExamplesUse an ArrayList of Integer values to store int values. An ArrayList cannot store ints.
ArrayList, int. An ArrayList contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int).
Int notes. To place ints in ArrayList, we must convert them to Integers. This can be done in the add() method on ArrayList. Each int must added individually.
First example. Here we have an int array. It has 3 values in it. We create an ArrayList and add those ints as Integers in a for-loop.
Detail The add() method receives an Integer. And we can pass an int to this method—the int is cast to an Integer.
import java.util.ArrayList; public class Program < public static void main(String[] args) < int[] ids = <-3, 0, 100>; ArrayList values = new ArrayList<>(); // Add all the ints as Integers with add. // . The ints are cast to Integer implicitly. for (int id: ids) < values.add(id); > System.out.println(values); // The collections have the same lengths. System.out.println(values.size()); System.out.println(ids.length); > >-3,>
For-loop. We can use a simpler syntax to loop over elements—the for-each loop does not have an index variable. This improves readability. But it reduces flexibility in the loop.
import java.util.ArrayList; public class Program < public static void main(String[] args) < ArrayList
Count, clear. The ArrayList is used in many programs. But in most places, it is used in a similar way: we instantiate, add elements, and access data.
Part 1 We create an ArrayList—diamond inference syntax is on the right side. We add 3 elements in statements.
Part 3 We call clear() to empty the ArrayList, and then print its size again. The ArrayList is empty.
import java.util.ArrayList; public class Program < public static void main(String[] args) < // Part 1: create new ArrayList. // . Add 3 elements. ArrayList elements = new ArrayList <> (); elements.add( 10 ); elements.add( 15 ); elements.add( 20 ); // Part 2: get count by calling size. System.out.println(«Count: « + elements.size()); // Part 3: clear and print size. elements.clear(); System.out.println(«Count: « + elements.size()); > >
IndexOf. We use the indexOf and lastIndexOf methods to find indexes. IndexOf searches from the beginning. LastIndexOf searches from the end.
Part 2 We search for values. IndexOf and lastIndexOf find different indexes because they search in different ways.
Part 3 We display the results. We see that when a value is not found, the special index -1 is returned.
import java.util.ArrayList; public class Program < public static void main(String[] args) < // Part 1: create ArrayList. ArrayList list = new ArrayList<>(); list.add( 101 ); list.add( 100 ); list.add( 99 ); list.add( 100 ); list.add( 99 ); // Part 2: search for values. int index = list.indexOf(100); int lastIndex = list.lastIndexOf(100); int notFound = list.indexOf(200); // Part 3: display results. System.out.println(«INDEX: « + index); System.out.println(«LASTINDEX: « + lastIndex); System.out.println(«NOTFOUND: « + notFound); > >
SubList. This returns a view of the ArrayList. We can loop over the returned List, or access its elements, using a zero-based index. So the first element in the sub-list is at index 0.
Argument 1 The first argument to subList() is the first index of the range we want to access from the ArrayList.
Argument 2 This is the last index (not a count) of the view we want to access from the source ArrayList.
Tip If we set() an element in the sub-list to a value, this is reflected in the original list. The indexes are automatically translated.
import java.util.ArrayList; import java.util.List; public class Program < public static void main(String[] args) < // . Add 5 integers to an ArrayList. ArrayList list = new ArrayList<>(); list.add(5); list.add(10); list.add(15); list.add(20); list.add(25); // . Get sub list from 1 to 3. List sub = list.subList( 1, 3 ); // . Display sub list. for (int value : sub) < System.out.println(value); >// . Set the first element in «sub» to -1. // This is reflected in the original ArrayList. sub.set(0, -1); System.out.println(list.get(1)); > >
Collections.min, max. Many static methods in the Collections class can be used on an ArrayList. Here we use two simple ones: min and max.
Detail This scans the entire collection (an ArrayList) and returns the value of the smallest element.
import java.util.ArrayList; import java.util.Collections; public class Program < public static void main(String[] args) < // Create ArrayList. ArrayList list = new ArrayList<>(); list.add(10); list.add(1); list.add(100); list.add(5); // Min and max. int minimum = Collections.min(list); int maximum = Collections.max(list); System.out.println(minimum); System.out.println(maximum); > >
Collections.addAll. With this we add many elements to an ArrayList at once. The second argument is either an array of the elements to add, or those elements as arguments.
import java.util.ArrayList; import java.util.Collections; public class Program < public static void main(String[] args) < ArrayList
ToArray. The toArray method copies an ArrayList’s elements to an array. It has two versions—one returns an Object array and requires casting. This version, though, returns a typed array.
Tip The toArray method will allocate a new array and return its reference unless it receives a large enough array.
So We use toArray by passing it an empty array of the matching type. It then returns a correctly-sized array.
import java.util.ArrayList; import java.util.List; public class Program < public static void main(String[] args) < ArrayList
Compile error. We cannot specify int as the type of an ArrayList. An int is not a «ReferenceType.» Instead we must use Integer—and add only Integers to this collection.
Exception in thread «main» java.lang.Error: Unresolved compilation problem: Syntax error, insert «Dimensions» to complete ReferenceType at Program.main(Program.java:8)
AddAll error. We cannot pass an int array to the Collections.addAll method to add Integers to an ArrayList. An Integer array can be used.
Note To add ints we need some extra steps to enable conversion from int to Integer. A for-loop with add() is effective.
import java.util.ArrayList; import java.util.Collections; public class Program < public static void main(String[] args) < int[] ids = <-3, 0, 100>; ArrayList values = new ArrayList<>(); // This does not compile. // . Integer is not the same as int. Collections.addAll(values, ids); > >-3,>
Exception in thread «main» java.lang.Error: Unresolved compilation problem: The method addAll(Collection, T. ) in the type Collections is not applicable for the arguments (ArrayList, int[]) at Program.main(Program.java:11)?>
Notes, Integer. What is an Integer? And why cannot we use int in an ArrayList? An Integer is a reference type (a class). An int is a value.
A summary. With the Integer class, we store ints in an ArrayList. We cannot use int directly. This introduces some complexity to our programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
ArrayList в Java
ArrayList — реализация изменяемого массива интерфейса List, часть Collection Framework, который отвечает за список (или динамический массив), расположенный в пакете java.utils. Этот класс реализует все необязательные операции со списком и предоставляет методы управления размером массива, который используется для хранения списка. В основе ArrayList лежит идея динамического массива. А именно, возможность добавлять и удалять элементы, при этом будет увеличиваться или уменьшаться по мере необходимости.
Что хранит ArrayList?
Только ссылочные типы, любые объекты, включая сторонние классы. Строки, потоки вывода, другие коллекции. Для хранения примитивных типов данных используются классы-обертки.
Конструкторы ArrayList
ArrayList list = new ArrayList<>();
ArrayList list2 = new ArrayList<>(list);
ArrayList list2 = new ArrayList<>(10000);
Методы ArrayList
Ниже представлены основные методы ArrayList.
ArrayList list = new ArrayList<>(); list.add("Hello");
ArrayList secondList = new ArrayList<>(); secondList.addAll(list); System.out.println("Первое добавление: " + secondList); secondList.addAll(1, list); System.out.println("Второе добавление в середину: " + secondList);
Первое добавление: [Amigo, Hello] Второе добавление в середину: [Amigo, Amigo, Hello, Hello]
ArrayList copyOfSecondList = (ArrayList) secondList.clone(); secondList.clear(); System.out.println(copyOfSecondList);
System.out.println(copyOfSecondList.contains("Hello")); System.out.println(copyOfSecondList.contains("Check"));
// Первый способ for(int i = 0; i < secondList.size(); i++) < System.out.println(secondList.get(i)); >И цикл for-each: // Второй способ for(String s : secondList)
В классе ArrayList есть метод для обработки каждого элемента, который называется также, forEach. В качестве аргумента передается реализация интерфейса Consumer, в котором нужно переопределить метод accept():
secondList.forEach(new Consumer() < @Override public void accept(String s) < System.out.println(s); >>);
Метод accept принимает в качестве аргумента очередной элемент того типа, который хранит в себе ArrayList. Пример для Integer:
ArrayList integerList = new ArrayList<>(); integerList.forEach(new Consumer() < @Override public void accept(Integer integer) < System.out.println(integer); >>);
String[] array = new String[secondList.size()]; secondList.toArray(array); for(int i = 0; i
Ссылки на дополнительное чтение
- Подробная статья о динамических массивах, а точнее — об ArrayList и LinkedList , которые выполняют их роль в языке Java.
- Статья об удалении элементов из списка ArrayList.
- Лекция о работе с ArrayList в схемах и картинках.