REMEMBER JAVA

MINTE9
2REMEMBER




Last update:   27-07-2021

ARRAYLIST

p132 Java SE pre-build classes are just your own code, except there are already compiled. The ArrayList class is a resizable array, which can be found in the java.util package.
 RunCode
import java.util.ArrayList;

class LearningApp {

    public static void main(String[] args) {
        
        // special syntax (Generics)
        ArrayList<String> myList = new ArrayList<String>();
            
        String x = "a";
        String y = "b";
        
        myList.add(x);
        myList.add(y);
        
        System.out.printf("%s %s %s %s ", 

            myList.size(), // 2
            myList.contains(y), // true
            myList.indexOf(y), // 1 
            myList.isEmpty() // false
        );

        myList.remove(x); // remove
        System.out.println(

            myList.contains(x) // false
        );
    }
}
... 21 lines
˄˄˄
p137 ArrayList don't need a size.
 RunCode
import java.util.ArrayList;
        
class LearningApp {
    
    public static void main(String[] args) {
        
        String[] myList;
        myList = new String[2]; // Correct
        // myList = new String[]; // Error: dimension missing

        ArrayList<String> myArrayList;
        myArrayList = new ArrayList<String>(); // no dimension

        System.out.print(myArrayList.size()); // 0
    }
}
... 11 lines
˄˄˄
ArrayList don't need an index.
 RunCode
import java.util.ArrayList;
        
class LearningApp {
    
    public static void main(String[] args) {
        
        String[] myList = new String[2];
        myList[0] = "a";
        myList[1] = "b";

        ArrayList<String> myArrayList = new ArrayList<String>();
        myArrayList.add("a"); // no index needed
        myArrayList.add("b");

        System.out.print(myArrayList.size()); // 2
    }
}
... 12 lines
˄˄˄
ArrayList objects are parameterized.
 RunCode
import java.util.ArrayList;
        
class LearningApp {
    
    public static void main(String[] args) {
        
        ArrayList<String> myStrings = new ArrayList<String>();
       
        ArrayList<Button> myButtons = new ArrayList<Button>();
    }
}

class Button {}
... 8 lines
˄˄˄
Loop    (2/2)

Loop

You can also loop through an ArrayList with the for-each loop.
 RunCode
import java.util.ArrayList;  // import class
        
class LearningApp {
    
    public static void main(String[] args) {
        
        ArrayList<String> myList = new ArrayList<String>();

        String x = "a";
        String y = "b";
        String z = "c";

        myList.add(x);
        myList.add(y);
        myList.add(0, z); // add to first position

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

ArrayDeque

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.
Questions    
No. 23   Collection
CARD
22

        A B C D E F
🔔
1/3