Как изменить размер arraylist java

I come from a C++ background and I want to have a matrix of ArrayList<arrayList> javamatrix In C++ I would just do std::vector<std::vector > cppmatrix; std::vecto...

I come from a C++ background and I want to have a matrix of

ArrayList<arrayList<E>> javamatrix 

In C++ I would just do

std::vector<std::vector<T> > cppmatrix;
std::vector<T>vcol(cols);
cppmatrix.resize(rows,vcol);

I can’t seem to find a built-in resize() function for ArrayLists for this task, so should I use another collection? Is no way to do this except using for loops with javamatrix.add()?


P.S I want it to be initialized in the constructor with its size as that size might be queried before I edit elements or add or remove.

apxcode's user avatar

apxcode

7,6287 gold badges30 silver badges41 bronze badges

asked Nov 13, 2010 at 1:51

Ismail Marmoush's user avatar

Ismail MarmoushIsmail Marmoush

12.9k25 gold badges79 silver badges112 bronze badges

3

There is no resize equivalent that automatically constructs and adds elements. You must do this yourself. However, ensureCapacity is equivalent to vector’s reserve. It will ensure you have room, but not change the actual size.

answered Nov 13, 2010 at 2:01

Matthew Flaschen's user avatar

Matthew FlaschenMatthew Flaschen

274k50 gold badges513 silver badges537 bronze badges

0

You shouldn’t need to resize arraylists. The size you initially pass in is just its starting size. If you attempt to add items beyond its current size, it will automatically resize.

From the documentation:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

answered Nov 13, 2010 at 1:55

Dave McClelland's user avatar

Dave McClellandDave McClelland

3,3551 gold badge28 silver badges44 bronze badges

3

Mostly, a ‘resize()’ operation is not needed because (a) ArrayList’s auto-resize as you add elements, and (b) it’s unclear what values you would store in the ArrayList<>, e.g. ‘null’ is not very useful. E.g. in your case you’d probably need a loop anyway to create MatrixCell objects.

For those readers who want to know how to resize an ArrayList to make it smaller, it mystifies me why ArrayList was designed without a ‘resize()’ method. Perhaps it’s because novice programmers are likely to see that method and then not realise that ArrayList<> auto-resizes.

In Java this idiom works to reduce the size of an ArrayList<>:

    list.subList(n,list.size()).clear();

It works because the ‘subList’ returns a List backed by the original ArrayList<>, so therefore the ‘clear()’ operates on the original ‘ArrayList<>’.

answered Apr 23, 2013 at 1:39

Tim Cooper's user avatar

5

I know this question is very old already but this link may help java arraylist ensureCapacity not working , The code adds «Null» value in order to adjust the current size.

Instead of using purely ensureCapacity you can have ensureSize

public static void ensureSize(ArrayList<?> list, int size) {

    list.ensureCapacity(size);
    while (list.size() < size) {
        list.add(null);
    }
}

Community's user avatar

answered Jan 14, 2015 at 3:01

neferpitou's user avatar

neferpitouneferpitou

1,6022 gold badges20 silver badges25 bronze badges

1

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.

    Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold. However, ensureCapacity() method of java.util.ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

    Syntax:

    public void ensureCapacity(int minCapacity)

    Parameters: This method takes the desired minimum capacity as a parameter.

    Return Type: This method does not return any value.

    Example:

    Java

    import java.util.ArrayList;

    public class GFG {

        public static void main(String[] arg) throws Exception

        {

            try {

                ArrayList<String> numbers

                    = new ArrayList<String>(3);

                numbers.add("10");

                numbers.add("20");

                numbers.add("30");

                System.out.println("ArrayList: " + numbers);

                System.out.println(

                    "Increasing the capacity of ArrayList numbers to store upto 500 elements.");

                numbers.ensureCapacity(500);

                System.out.println(

                    "ArrayList numbers can now store upto 500 elements.");

            }

            catch (NullPointerException e) {

                System.out.println("Exception thrown : " + e);

            }

        }

    }

    Output

    ArrayList: [10, 20, 30]
    Increasing the capacity of ArrayList numbers to store upto 500 elements.
    ArrayList numbers can now store upto 500 elements.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.

    Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold. However, ensureCapacity() method of java.util.ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

    Syntax:

    public void ensureCapacity(int minCapacity)

    Parameters: This method takes the desired minimum capacity as a parameter.

    Return Type: This method does not return any value.

    Example:

    Java

    import java.util.ArrayList;

    public class GFG {

        public static void main(String[] arg) throws Exception

        {

            try {

                ArrayList<String> numbers

                    = new ArrayList<String>(3);

                numbers.add("10");

                numbers.add("20");

                numbers.add("30");

                System.out.println("ArrayList: " + numbers);

                System.out.println(

                    "Increasing the capacity of ArrayList numbers to store upto 500 elements.");

                numbers.ensureCapacity(500);

                System.out.println(

                    "ArrayList numbers can now store upto 500 elements.");

            }

            catch (NullPointerException e) {

                System.out.println("Exception thrown : " + e);

            }

        }

    }

    Output

    ArrayList: [10, 20, 30]
    Increasing the capacity of ArrayList numbers to store upto 500 elements.
    ArrayList numbers can now store upto 500 elements.

    In this post, I am going to demonstrate how the size of the ArrayList increases dynamically?

    The ArrayList size increases dynamically because whenever the ArrayList class requires to resize then it will create a new array of bigger size and copies all the elements from the old array to the new array. And now it is using the new array’s reference for its internal usage. As the old array is no longer in use, it will be garbage collected in the next garbage collection.

    Let’s see how ArrayList size increases dynamically in detail.

    As we know that Array is fixed length data structure and once it is created, we can’t change its size but ArrayList can re-size itself when gets full depending upon capacity and load factor.

    Basically, the ArrayList is a resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

    Let’s create an example of ArrayList with default Constructor to know the default size of 10.

    Create an ArrayList Example — usage of add() method

    public class CreateArrayListExample {
    
        public static void main(String[] args) {
            // Creating an ArrayList of String using
         List<String> animals = new ArrayList<>();
            // Adding new elements to the ArrayList
            animals.add("Lion");
            animals.add("Tiger");
            animals.add("Cat");
            animals.add("Dog");
    
            System.out.println(animals);
    
            // Adding an element at a particular index in an ArrayList
            animals.add(2, "Elephant");
    
            System.out.println(animals);
        }
    }

    Output:

    [Lion, Tiger, Cat, Dog]
    [Lion, Tiger, Elephant, Cat, Dog]
    

    From the above example, the default constructor is used to create an ArrayList instance. 

    new ArrayList<>(); — Constructs an empty list with an initial capacity of ten.

    ArrayList internal Implementation

    Let’s take a look at, what is present inside the ArrayList class. We will be looking at implementations according to Java 8. 

    Steps to see in the internal implementation of an ArrayList class

    1. Find the DEFAULT_CAPACITY of the ArrayList
    2. ArrayList increase the size dynamically while adding the elements to it, so look at the internal working of add() method.
    3. Look at source code of ArrayList and how it grows its size?

    This source code is copied from ArrayList implementation class to demonstrate how ArrayList grows dynamically(JDK 8 version).

    Find the DEFAULT_CAPACITY of the ArrayList

    Observe the DEFAULT_CAPACITY instance variable in aisigned with value 10.

     /**
         * Default initial capacity.
         */
        private static final int DEFAULT_CAPACITY = 10;

    Internal working add() method

    As more and more elements are added to the ArrayList, the size of the array keeps on increasing. How does that happen ?

    Lets take a look at the add method :

    /**
         * Appends the specified element to the end of this list.
         *
         * @param e element to be appended to this list
         * @return <tt>true</tt> (as specified by {@link Collection#add})
         */
        public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            elementData[size++] = e;
            return true;
        }

    Also look at how ArrayList inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

        /**
         * Inserts the specified element at the specified position in this
         * list. Shifts the element currently at that position (if any) and
         * any subsequent elements to the right (adds one to their indices).
         *
         * @param index index at which the specified element is to be inserted
         * @param element element to be inserted
         * @throws IndexOutOfBoundsException {@inheritDoc}
         */
        public void add(int index, E element) {
            rangeCheckForAdd(index);
    
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            System.arraycopy(elementData, index, elementData, index + 1,
                             size - index);
            elementData[index] = element;
            size++;
        }

    Whenever the add method is called, it makes a internal call to the private ensureCapacityInternal method and passes existing size+1 as a method argument. 

    The ensureCapacityInternal() method internally makes a call to private ensureExplicitCapacity(int minCapacity) method.

     private void ensureCapacityInternal(int minCapacity) {
            ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
     }
    
     private void ensureExplicitCapacity(int minCapacity) {
            modCount++;
    
            // overflow-conscious code
            if (minCapacity - elementData.length > 0)
                grow(minCapacity);
        }

    The ensureExplicitCapacity() checks the condition theminCapacity — elementData.length > 0 , if it is true then it calls the grow() method to increase the size.

    The grow method creates a new Array of size int newCapacity = oldCapacity + (oldCapacity >> 1) and then copy all the elements in the new array from the older one.

     /**
         * Increases the capacity to ensure that it can hold at least the
         * number of elements specified by the minimum capacity argument.
         *
         * @param minCapacity the desired minimum capacity
         */
        private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
        private static int hugeCapacity(int minCapacity) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
        }

    So the backing array is not growing, every time when it is full, The ArrayList class is creating a new array of bigger size and copies all the elements from the old array to the new array. And now it is using the new array’s reference for its internal usage. As the old array is no longer in use, it will be garbage collected in the next garbage collection.

    1. Изменить размер массива в Java
    2. Измените размер массива с помощью метода arraycopy() в Java
    3. Изменение размера массива с помощью метода copyOf() в Java
    4. Изменение размера массива с помощью цикла for в Java

    Изменение размера массива с сохранением текущих элементов в Java

    В этом руководстве показано, как изменить размер массива, сохранив все его текущие элементы в Java. Мы включили несколько примеров программ, на которые вы можете ссылаться при выполнении программы в этом поле.

    Массив определяется как контейнер, используемый для хранения подобных типов элементов в Java. Это контейнер фиксированного размера, что означает, что если массив имеет размер 10, он может хранить только 10 элементов — это одно из ограничений массива.

    В этой статье мы научимся изменять размер массива с помощью некоторых встроенных методов, таких как функции arraycopy() и copyOf(), а также некоторых пользовательских кодов.

    Изменить размер массива в Java

    Самая верхняя альтернатива динамического массива — это класс структуры коллекции ArrayList, который может хранить любое количество элементов и динамически увеличивается. Первое, что мы можем сделать, это создать ArrayList и скопировать в него все элементы массива. Наконец-то у нас появился новый размер массива. См. Пример ниже:

    import java.util.ArrayList;
    import java.util.List;
    public class SimpleTesting{
        public static void main(String[] args) {
            int arr[] = new int[]{12,34,21,33,22,55};
            for(int a: arr) {
                System.out.print(a+" ");
            }
            List<Integer> list = new ArrayList<>();
            for(int a: arr) {
                list.add(a);
            }
            System.out.println("n"+list);
            list.add(100);
            System.out.println(list);
        }
    }
    

    Выход:

    12 34 21 33 22 55 
    [12, 34, 21, 33, 22, 55]
    [12, 34, 21, 33, 22, 55, 100]
    

    Измените размер массива с помощью метода arraycopy() в Java

    Java предоставляет метод arraycopy(), который принадлежит классу System и может использоваться для создания копии массива. В этом примере мы создаем новый массив большего размера, а затем копируем в него все исходные элементы массива с помощью метода arraycopy(). Следуйте приведенному ниже примеру программы:

    public class SimpleTesting{
        public static void main(String[] args) {
            int arr[] = new int[]{12,34,21,33,22,55};
            for(int a: arr) {
                System.out.print(a+" ");
            }
            int arr2[] = new int[10];
            System.arraycopy(arr, 0, arr2, 0, arr.length);
            System.out.println();
            for(int a: arr2) {
                System.out.print(a+" ");
            }
            System.out.println();
            arr2[6] = 100;
            for(int a: arr2) {
                System.out.print(a+" ");
            }
        }
    }
    

    Выход:

    12 34 21 33 22 55
    12 34 21 33 22 55 0 0 0 0
    12 34 21 33 22 55 100 0 0 0
    

    Изменение размера массива с помощью метода copyOf() в Java

    Класс Java Arrays предоставляет метод copyOf(), который можно использовать для создания массива нового размера путем копирования всех исходных элементов массива. Этот процесс принимает два аргумента: первый — это исходный массив, а второй — размер нового массива. См. Пример ниже:

    import java.util.Arrays;
    public class SimpleTesting{
        public static void main(String[] args) {
            int arr[] = new int[]{12,34,21,33,22,55};
            for(int a: arr) {
                System.out.print(a+" ");
            }
            int arr2[] = Arrays.copyOf(arr, 10);
            System.out.println();
            for(int a: arr2) {
                System.out.print(a+" ");
            }
            System.out.println();
            arr2[6] = 100;
            for(int a: arr2) {
                System.out.print(a+" ");
            }
        }
    }
    

    Выход:

    12 34 21 33 22 55 
    12 34 21 33 22 55 0 0 0 0 
    12 34 21 33 22 55 100 0 0 0 
    

    Изменение размера массива с помощью цикла for в Java

    Этот метод прост и является более старым подходом, в котором мы используем цикл for и присваиваем исходные элементы массива вновь созданному массиву на каждой итерации. Мы просто создаем новый массив большего размера и копируем в него все элементы с помощью цикла. См. Пример ниже:

    public class SimpleTesting{
        public static void main(String[] args) {
            int arr[] = new int[]{12,34,21,33,22,55};
            for(int a: arr) {
                System.out.print(a+" ");
            }
            int arr2[] = new int[10];
            for (int i = 0; i < arr.length; i++) {
                arr2[i] = arr[i];
            }
            System.out.println();
            for(int a: arr2) {
                System.out.print(a+" ");
            }
        }
    }
    

    Выход:

    12 34 21 33 22 55 
    12 34 21 33 22 55 0 0 0 0
    

    In this Collection framework tutorial we will learn what is the default initial capacity of ARRAYLIST, how it is resized and size is increased in java.

    Contents of page >

    • 1) What is meaning of capacity in ArrayList in java?

    • 2) Does size of ArrayList grows automatically in java?

    • 3) What is default initial capacity of ArrayList in java?

    • 4) By what size ArrayList is resized in java? How much size increases when ArrayList is resized in java?

    • 5) But how ArrayList is resized in java?

    • 6) Let’s see java Example/program to see what is default initial capacity of ArrayList in java and how it is resized in java by putting java application debug mode?

    • 7) Can we change default initial capacity of ArrayList in java?

    • 8) Can we change resizing of ArrayList in java? The amount by which the capacity of ArrayList is increased when the ArrayList overflows?

    • 9) Should you change default initial capacity of ArrayList in java?

    • 10) How ArrayList is implemented in java?

    • 11) One more important concept related to ArrayList size, a MUST READ discussion on java.util.ArrayList internal methods >

    1) What is meaning of capacity in ArrayList in java?

    Capacity is the size of the array which is used to store elements in the ArrayList.

    2) Does size of ArrayList grows automatically in java?

    Yes, size of ArrayList grows automatically in java. ArrayList resizes itself dynamically in java.

    3) What is default initial capacity of ArrayList in java?

    Default initial capacity of ArrayList is 10.

    java.util.ArrayList defines private static final variable DEFAULT_CAPACITY to define initial capacity of ArrayList.

       /**

        * Default initial capacity.

        */

    private static final int DEFAULT_CAPACITY = 10;

    4) By what size ArrayList is resized in java? How much size increases when ArrayList is resized in java?

    ArrayList is resized by 50% of it’s current size.

    So, ArrayList will be resized from 10, to 15, to 22, to 33 and so on.

    5) But how ArrayList is resized in java?

    ArrayList’s add method internally calls ensureCapacityInternal method, which calls ensureExplicitCapacity method, which calls grow method, grow method >

    • creates new array of higher capacity and

    • copies existing array to new one and

    • return the new array.

    6) Let’s see java Example/program to see what is default initial capacity of ArrayList in java and how it is resized in java by putting java application debug mode?

    import java.util.ArrayList;

    import java.util.List;

    public class ArrayListDefaultCapacityAndResizingExample {

    public static void main(String args[]) {

         List<Integer> arrayList = new ArrayList<Integer>();

         for (int i = 1; i < 25; i++) {

              arrayList.add(i);

         }

    }

    }

    When, new ArrayList<Integer>() is executed, Size of ArrayList is 0.

    As soon as first element is added, using add(i), where i=1, ArrayList is initialized to it’s default capacity of 10.

    Till addition of 10th element size of ArrayList remains same.

    As soon as 11th element is added, using add(i), where i=11, ArrayList is resized to 15.

    Till addition of 15th element size of ArrayList remains same.

    As soon as 16th element is added, using add(i), where i=16, ArrayList is resized to 22.

    Till addition of 22th element size of ArrayList remains same.

    As soon as 23rd element is added, using add(i), where i=23, ArrayList is resized to 33.

    7) Can we change default initial capacity of ArrayList in java?

    Yes, rather than using new ArrayList(), you can use other constructor specified in java.util.ArrayList

       public ArrayList(int initialCapacity) {

           super();

           if (initialCapacity < 0)

            throw new IllegalArgumentException(«Illegal Capacity: «+

                                               initialCapacity);

           this.elementData = new Object[initialCapacity];

       }

    This constructor will throw IllegalArgumentException if initialCapacity passed is less than 0.

    8) Can we change resizing of ArrayList in java? The amount by which the capacity of ArrayList is increased when the ArrayList overflows?

    No.

    9) Should you change default initial capacity of ArrayList in java?

    Well that is opinion based questions, but default size offers best tradeoff between memory occupied and performance.

    I’ll recommend you to go for default initial capacity offered by ArrayList in java.

    Keeping ArrayList size very less can be a huge performance set back, because it will be resized very rapidly.

    Example — when it’s initial capacity is kept as 2, on addition of further elements it will be resized to 3,  then 4, then 6, then 9, then 13, then 19 and so on.

    So we saw that resizing of ArrayList was done so rapidly and it may significantly slow down your java application.

    But, huge enterprise application which is likely to store high number of objects may be benefited by increasing the default initial capacity offered by  ArrayList in java.

    10) How ArrayList is implemented in java?

    In this Collection framework tutorial we learned what is the default initial capacity of ARRAYLIST, how it is resized and size is increased in java.

    11) One more important concept related to ArrayList size, a MUST READ discussion on java.util.ArrayList internal methods >

    When, new ArrayList<Integer>() is executed, Size of ArrayList is 0.

    Internally, When you call new ArrayList<Integer>() the constructor of ArrayList is called>

       public ArrayList() {

           super();

           this.elementData = EMPTY_ELEMENTDATA;

       }

    Here we can see that initial size is EMPTY_ELEMENTDATA (its value is {} — i.e. 0 elements).

    As soon as first element is added, using add(i), where i=1, ArrayList is initialized to it’s default capacity of 10.

       public boolean add(E e) {

           ensureCapacityInternal(size + 1);  // Increments modCount!!

           elementData[size++] = e;

           return true;

       }

       private void ensureCapacityInternal(int minCapacity) {

           if (elementData == EMPTY_ELEMENTDATA) {

            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);

           }

           ensureExplicitCapacity(minCapacity);

       }

    When add method is called, it internally calls ensureCapacityInternal method,
    which further checks if elementData is equal to EMPTY_ELEMENTDATA (i.e. 0), then it assigns it value of DEFAULT_CAPACITY (using Math.max method initially the value is  10.)

    Having any doubt? or you you liked the tutorial! Please comment in below section.

    RELATED LINKS>

    List hierarchy in java — Detailed — ArrayList, LinkedList, vector, CopyOnWriteArrayList classes

    ArrayList vs LinkedList — Similarity and Differences

    ArrayList vs Vector — Similarity and Differences

    ArrayList vs CopyOnWriteArrayList — Similarity and Differences with program

    Consequence of using ArrayList in multithreading environment in java

    ArrayList Programs >
    ArrayList — add, add element at specific index methods program
    ArrayList — remove, get, contains and set methods program
    ArrayList — iterate using iterator, listIterator, Enumeration and enhanced for loop
    ArrayList — fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop

    Афоризм

    Он отступал вполне победоносно.

    Поддержка проекта

    Если Вам сайт понравился и помог, то будем признательны за Ваш «посильный» вклад в его поддержку и развитие

     • Yandex.Деньги
      410013796724260

     • Webmoney
      R335386147728
      Z369087728698

    В Java массивы имеют фиксированную длину и не могут быть увеличены или уменьшены. Класс ArrayList
    реализует интерфейс List и может менять свой размер во время исполнения программы, при этом не
    обязательно указывать размерность при создании объекта. Элементы ArrayList могут быть абсолютно любых типов
    в том числе и null.

    Пример создания объекта ArrayList

    ArrayList <String> list = new ArrayList <String>();
    

    Можно инициализировать массив на этапе определения. Созданный объект list содержит свойство size.
    Обращение к элементам массива осуществляется с помощью метода get(). Пример :

    ArrayList <String> list;
    list = Arrays.asList(new String[] {"a", "b", "c"});
    System.out.println ("Размер массива равен '" + 
                Integer.valueOf (list.size()) + "' элементам");
    

    Добавление элемента в массив ArrayList, метод add

    Работать с ArrayList просто: необходимо создать объект и вставлять созданные объекты методом add().
    Обращение к элементам массива осуществляется с помощью метода get(). Пример:

    ArrayList <String> list;
    list = new ArrayList <String();
    list.add("Школа");
    System.out.println ("Первый элемент массива '" 
                                    + list.get(0) + "'");
    System.out.println ("Размер массива '" 
                  + Integer.valueOf (list.size()) + "'");
    

    Замена элемента массива ArrayList, метод set

    Чтобы заменить элемент в массиве, нужно использовать метод set() с указанием индекса и новым значением.

    list.add("Яблоко");
    list.add("Груша");
    list.add("Слива");
    
    list.set(1, "Персик");
    
    System.out.println (
               "2-ой элемент массива '" + list.get(1) + "'");
    

    Удаление элемента массива ArrayList, метод remove

    Для удаления элемента из массива используется метод remove(). Можно удалять по индексу или по объекту:

    list.remove(0);       // удаляем по индексу
    list.remove("Слива"); // удаляем по объекту
    

    ПРИМЕЧАНИЕ: элементы, следующие после удалённого элемента, перемещаются
    на одну позицию ближе к началу. То же самое относится и к операции вставки элемента в середину списка.

    Для очистки всего массива используется метод clear():

    Определение позиции элемента ArrayList, метод indexOf

    В списочном массиве ArrayList существует метод indexOf(), который ищет нужный элемент и возвращает
    его индекс.

    int index = list.indexOf("Слива");  
    
    // выводим имя элемента и его номер в массиве
    System.out.println (list.get(index) + 
                   " числится под номером " + index);
    

    Отсчёт в массиве начинается с 0, если индекс равен 2, значит он является третьим в массиве.

    Проверка наличие элемента в ArrayList, метод contains

    Чтобы узнать, есть в массиве какой-либо элемент, можно воспользоваться методом contains(), который
    вернёт логическое значение true или false в зависимости от присутствия элемента в наборе :

    System.out.println (list.contains("Картошка") + "");
    

    Понятно, что в массиве никаких овощей быть не может, поэтому в консоле будет отображено false.

    Создание массива из элементов ArrayList, метод toArray

    Для конвертирования набора элементов в обычный массив необходимо использовать метод toArray().

    ArrayList<String> myArrayList = new ArrayList<String>();
    myArrayList.add("Россия");
    myArrayList.add("Польша");
    myArrayList.add("Греция");
    myArrayList.add("Чехия");
    
    String[] array = {}; // конвертируем ArrayList в массив
    array = myArrayList.toArray(new String[myArrayList.size()]);
    

    Интерфейс List

    java.util.List является интерфейсом и его следует использовать вместо ArrayList следующим образом :

    List<String> list = new ArrayList<String>();
    

    Или укороченный вариант для Java 7:

    List<String> list = new ArrayList<>();
    

    В примере тип ArrayList заменен на List, но в объявлении оставлен new ArrayList(). Всё остальное
    остаётся без изменений. Это является рекомендуемым способом.

    Интерфейс List реализует более общий интерфейс коллекции Collection.

    Преобразование массива в список, Arrays

    Для создания массива можно не только добавлять по одному объекту через метод add(), но и сразу массив с использованием
    Arrays.asList(…).

    Пример создания и инициализации массива из объектов Integer.

    List<Integer> numlist = Arrays.asList(1, 2, 5, 9, 11);
    
    System.out.println (numlist.get(2) + ""); // выводит число 5
    

    У данного способа есть недостаток. Если вы определили списочный массив таким образом, то уже не можете вставлять или удалять
    элемент, хотя при этом можете изменять существующий элемент.

    List<Integer> numlist = Arrays.asList(1, 2, 5, 9, 11);
    numlist.set(2, 33); // так можно
    numlist.add(34);    // нельзя, ошибка во время исполнения
    
    System.out.println (numlist.get(2) + "");
    

    Наверх

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить разделы на внешнем жестком диске
  • Как изменить разделы диска на виндовс 7
  • Как изменить разделы word
  • Как изменить разделы hdd
  • Как изменить разделение экрана minecraft ps4

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии