Home | 7.1 Introduction | 7.2 Methods | 7.3 Traversing | 7.4 Algorithms | 7.5 Searching | 7.6 Sorting | 7.7 Ethical Issues |
7.1 ArrayList Intro
Introduction to ArrayLists
7.1: ArrayList Intro
- ArrayLists are dynamic (size can grow and shrink unlike arrays which are static)
- Instead of creating a different size array each time, we can use ArrayLists!
- Ex: You and ur beautiful wife…
In order to use the ArrayList class, it needs to be imported from the java util package. This can be done by writing import java.util.ArrayList; at the beginning of the code
- To use Arraylist class, it needs to be imported from java.util package
- At beginning of code using an Arraylist, type the command below!
import java.util.ArrayList;
// your amazing code here!
ArrayList objects are initialized the same way as most object classes. However, the element type (String, Integer, Boolean) must be specified in the <>. Look at the example below, where the element type is String in this case.
- Arraylist objects are initialized like most object classes
- The objects can’t store primitive types directly
- the element type must be initialized in <>
ArrayList<String> awesomeword = new ArrayList(); // example of initializing an arraylist of strings called "awesomeword"
Popcorn Hack #1
What’s wrong with the code below?
import java.util.ArrayList;
ArrayList<String> awesomeword = new ArrayList();
ArrayList<Integer> coolnumbers = new ArrayList();
ArrayList<Boolean> truefalse = new ArrayList();
// comment answer when doing the homework
Its missing a parameter. With an arraylist you must include a paramerter such as a < string >
ArrayLists can be created without specifying a type, allowing them to hold any object type. However, its better to define the type because it allows the compiler to catch errors at compile time whcich makes the code more efficient and easier to debug. Example is below
- Arraylists can be created without specifying a type (they can hold any)
- Better to define the type as it makes code easier to debug and more efficient
ArrayList list = new ArrayList(); // no object type specified!
Popcorn Hack #2
Create 2 ArrayLists, one with an integer type called “sritestgrades” and other string type called “srihobbies
import java.util.ArrayList;
ArrayList<Integer> sritestgrades = new ArrayList<>(); // change the question marks
ArrayList<String> srishobbies = new ArrayList<>();
sritestgrades.add(45);
sritestgrades.add(32);
sritestgrades.add(1);
sritestgrades.add(90);
sritestgrades.add(74);
srishobbies.add("watching netflix");
srishobbies.add("sleeping");
srishobbies.add("coding");
srishobbies.add("annoying saathvik");
// Printing the values
System.out.println("Sri's Test Grades are: " + sritestgrades);
System.out.println("Sri's Hobbies are: " + srishobbies);
Sri's Test Grades are: [45, 32, 1, 90, 74]
Sri's Hobbies are: [watching netflix, sleeping, coding, annoying saathvik]