PROGRAMMING

  MINTE9
REMEMBERS




Last update:   29-10-2021

Size

p132 ArrayList don't need a size.
 
/**
 * ArrayList class is a resizable array,
 * ArrayList don't need an index and are parameterized.
 */

package com.minte9.collections.lists;

import java.util.ArrayList;

public class Size {    
    public static void main(String[] args) {
        
        String[] myList = new String[2]; // Corect, with dimension
        System.out.println(myList.length); // 2

        // myList = new String[]; // Error: must provide dimension

        ArrayList<String> myArrayList;
        myArrayList = new ArrayList<>(); // no dimension needed
        System.out.println(myArrayList.size()); // 0

        myArrayList.add("a");
        System.out.println(myArrayList.size()); // 1
        System.out.println(myArrayList.contains("a")); // true

        ArrayList<Button> myButtons = new ArrayList<>(); // parameterized
        myButtons.add(new Button());
        System.out.println(myButtons.size()); // 1
    }
}

class Button {

}

Loop

You can loop through an ArrayList with the enhanced for.
 
/**
 * ArrayList can be parsed easily with enhanced for.
 * 
 * ArrayDeque can add elements to the head as fast as to the tail.
 * If you are modifing the tail only, the ArrayList is a preferred.
 */

package com.minte9.collections.lists;

import java.util.ArrayDeque;
import java.util.ArrayList;

public class Loop {    
    public static void main(String[] args) {
        
        ArrayList<String> myList = new ArrayList<String>();
        myList.add("a");
        myList.add("b");
        myList.add(0, "c"); // add to first position

        for(String v:myList) {
            System.out.println(v); // c a b
        }

        ArrayDeque<Integer> myDeque = new ArrayDeque<>();
        myDeque.addFirst(1);
        myDeque.add(2);
        myDeque.addLast(10);
        myDeque.forEach(System.out::println); // 1 2 10
    }
}

Questions     github Collections
Comparable
        A B C D E F
🔔
1/3