Java Video Tutorial 11

Java Video Tutorial 11In this part of my Java Video Tutorial I introduce Java collection classes. Specifically I cover how to use Java ArrayLists.

Java ArrayLists make it easy to keep track of groups of objects. A Java ArrayList differs from a java array in that it automatically resizes itself when you add or remove values.

I’ll go over nearly every Java ArrayList method in the video below. The code follows the video and it is heavily commented to help you learn easily.

If you like videos like this share it

Code From the Video

// Collection classes were created to make it easy to keep track 
// of groups of objects. An ArrayList differs from an array in
// that it automatically resizes itself automatically. ArrayLists
// are easy to add to and delete from.

import java.util.ArrayList; // The ArrayList library
import java.util.Iterator; // The Iterator Library
import java.util.Arrays; // The Arrays Library

public class LessonEleven {
	
	public static void main(String[] args)
	{
		
		// You can create an ArrayList variable
		ArrayList arrayListOne;
		
		// Then create an ArrayList object
		// You don't have to declare the ArrayList size like you
		// do with arrays (Default Size of 10)
		arrayListOne = new ArrayList();
		
		// You can create the ArrayList on one line
		
		ArrayList arrayListTwo = new ArrayList();
		
		// You can also define the type of elements the ArrayList
		// will hold
		ArrayList<String> names = new ArrayList<String>();
		
		// This is how you add elements to an ArrayList
		names.add("John Smith");
		names.add("Mohamed Alami");
		names.add("Oliver Miller");
		
		// You can also add an element in a specific position
		names.add(2, "Jack Ryan");
		
		// You retrieve values in an ArrayList with get
		// arrayListName.size() returns the size of the ArrayList
		for( int i = 0; i < names.size(); i++)
		{
			System.out.println(names.get(i));
		}
		
		// You can replace a value using the set method
		names.set(0, "John Adams");
		
		// You can remove an item with remove
		names.remove(3);
		
		// You can also remove the first and second item with
		// the removeRange method
		// names.removeRange(0, 1);
		
		// When you print out the ArrayList itself the toString
		// method is called
		System.out.println(names);
		
		// You can also use the enhanced for with an ArrayList
		for(String i : names)
		{
			System.out.println(i);
		}
		System.out.println(); // Creates a newline
		
		// Before the enhanced for you had to use an iterator
		// to print out values in an ArrayList
		
		// Creates an iterator object with methods that allow
		// you to iterate through the values in the ArrayList
		Iterator indivItems = names.iterator();
		
		// When hasNext is called it returns true or false
		// depending on whether there are more items in the list
		
		while(indivItems.hasNext())
		{
			// next retrieves the next item in the ArrayList
			System.out.println(indivItems.next());
			
		}
		
		// I create an ArrayList without stating the type of values
		// it contains (Default is Object)
		ArrayList nameCopy = new ArrayList();
		ArrayList nameBackup = new ArrayList();
		
		// addAll adds everything in one ArrayList to another
		nameCopy.addAll(names);
		System.out.println(nameCopy);
		
		String paulYoung = "Paul Young";
		
		// You can add variable values to an ArrayList
		names.add(paulYoung);
		
		// contains returns a boolean value based off of whether
		// the ArrayList contains the specified object
		
		if(names.contains(paulYoung))
		{
			System.out.println("Paul is here");
		}
		
		// containsAll checks if everything in one ArrayList is in
		// another ArrayList
		if(names.containsAll(nameCopy))
		{
			System.out.println("Everything in nameCopy is in names");
		}
		
		// Clear deletes everything in the ArrayList
		names.clear();
		
		// isEmpty returns a boolean value based on if the ArrayList 
		// is empty
		if (names.isEmpty())
		{
			
			System.out.println("The ArrayList is empty");
			
		}
		
		Object[] moreNames = new Object[4];
		
		// toArray converts the ArrayList into an array of objects
		moreNames = nameCopy.toArray();
		
		// toString converts items in the array into a String
		System.out.println(Arrays.toString(moreNames));
		
		
	}
	
}

35 Responses to “Java Video Tutorial 11”

  1. nyprince says:

    HELLO AGAIN DEREK I WROTE TO YOU AND ASKED YOU THIS QUESTION BEFORE BUT I GUESS YOU’RE A BUSY MAN. I FOLLOWED THIS VIDEO TUTORIAL ON THE COLLECTIONS. YOU IMPORTED SEVERAL CLASS LIKE ITERATORS AND SUCH. CAN YOU IN THAT SITUATION JUST IMPORT JAVA.UTIL* FOR ALL THE CLASSES NECESSARY TO GET THE JOB DONE? THANKS

    • admin says:

      At the very least I think this would dramatically slow down your program. I’m going to check, but I’d advise against doing that. I must have missed one of your messages. Sorry about that

  2. duliocr says:

    Well Hello Derek
    Do you have an opinion of LearnNowJava.com is this a good or a bad investment. Thanks

  3. Anonymous says:

    Hey Derek i am a keen follower of your website,i just want to say that these tutorials are awesome and i hope u will put some programming tutorials on c++.God bless you.

  4. Aamir says:

    derek u have done an awesome job by developing this kind of website.God bless u!!

  5. Martin says:

    Hi master. I have small problem. How can I put objects from different classes to one ArrayList?

    http://pastebin.com/g0XzKp57 -here is a code

  6. MSkiLLz says:

    How many ArrayLists can you create in one file? If you can create more than one, then how do you specify which arraylist you are adding elements to? names.add() seems very general.

    Thanks.

  7. lidosurf says:

    Derek – you do a GREAT job with these lessons. Could you recommend a good text that might supplement your tutorials? Preferably a book with follow up exercises. thanks

  8. Niraj says:

    Object[] moreNames = new Object[4];
    moreNames = nameCopy.toArray();
    System.out.println(Arrays.toString(moreNames));

    Hey Derek,
    Tell me why do we need Object array to copy the arraylist into.

    I am getting the same thing by doing this.

    System.out.println(Arrays.toString(nameCopy.toArray()));

    any specific reason doing that way and also not giving the object array size doesnt make any difference.Even after putting 1 in the arraysize,the output is showing all the nameCopy list items.
    I dont understand what is going on at the backside.

  9. flipd.d.mon says:

    – Hi Derek –

    – Thank You for the tutorials – much obliged – !

    – Would You help me with ArrayLists further… – (?)

    – I have a scenario where I have a Vehicle Class with Vehicle Objects contained in an ArrayList – I have another Class, ‘Showroom’ to hold a Vehicle Objects ArrayList (The Showroom Constructor initialises the Vehicle Objects ArrayList) – I have managed to do this –

    – The Vehicles have an attribute (String) that contains their Registration / ID Number – I am able to search for a Vehicle Object, by passing the Registration Number attribute into a ‘findVehicle’ method in the Showroom Class –

    – I have to set a ‘currentVehicle’, again by passing in the Reg. No. attribute – I have managed to do this also –

    – the problem I am having though, is accessing / returning the next & previous Vehicle in the ArrayList –

    – I am wanting to have both a ‘nextVehicle’ & a ‘previousVehicle’ method that moves forward & backwards though the ArrayList from a start-point of the ‘currentVehicle’ –

    – When the ‘nextVehicle’ is returned, it is supposed to then become the ‘currentVehicle’ – likewise with the ‘previousVehicle’ method –

    – How might I iterate forwards & backwards through the ArrayList & return the appropriate Vehicle Object – (?)

    – I hope I have been clear… – I’m quite new to Java –

    – Any help is much appreciated –

    – Thanks –

    D.

    • flipd.d.mon says:

      – I need to clarify… – that the Vehicle Class has the Vehicle Attributes (e.g. Reg No. / Make / Model etc.), & the ArrayList of Vehicles is initialised by the Showroom Class –

      – Sorry if I’m not being clear –

      D.

    • Derek Banas says:

      I made a tutorial on how to set something like you want in Linked List in Java. It will also explain how an ArrayList works on an elementary level. I hope that helps 🙂

  10. navaneeth says:

    Hey Darek.. I just wanna say..
    Wohoooooo awesome work man.. (Y)

  11. saquib says:

    i didnt understand the math.random method. plz explain me.

    • Derek Banas says:

      To generate a random number using math.random you could do this to generate a number between 1 and 10 : int n = (int)(10.0 * Math.random()) + 1;

      This translates into int n = (int)(LargestNumber * Math.random()) + Smallest Number;

      Math.random() returns numbers between 0.0 to 0.999

      You could also use
      Random rand = new Random();
      int value = rand.nextInt(10);

      This gives you a number between 0 and 9. rand.nextInt(10) + 1; would give you numbers between 1 and 10.

      I hope that helps 🙂

  12. Fahad says:

    Hey Derek. I’m pretty new to Java, have only been programming for 3 days. My question is, at the moment my ArrayList only accepts Strings as I have set it to accept only Strings, How do I make my ArrayList accept both doubles Strings. code is as follows:

    //Name of class
    public class Profile{

    //Variables

    String Carbchoice = “rice”;
    double Height = 155.0;

    ArrayList arrayListOne = new ArrayList();

    ArrayList UserProfile = new ArrayList();

    //Method
    public void AddingToList(){

    UserProfile.add(CarbChoice);
    UserProfile.add(Height); //this is what I would like to do

    }
    }

    • Derek Banas says:

      You could use something like this ListyourList = new ArrayList (); or you could create a custom object that can contain doubles, or strings and use something like this List yourList = new ArrayList ();

  13. Charles-Alexis says:

    Is it possible to add String[] to an ArrayList? I tried but it does’nt seems to works.

Leave a Reply

Your email address will not be published.

Google+