Camposha
  • Home
  • Android
  • Buy Projects
  • My Account
    • Become a Member
    • Log In|Log Out
    • Free Projects
No Result
View All Result
Camposha
  • Home
  • Android
  • Buy Projects
  • My Account
    • Become a Member
    • Log In|Log Out
    • Free Projects
No Result
View All Result
Camposha
No Result
View All Result
ADVERTISEMENT
Home Java

Java ArrayList

2 years ago
in Java
Reading Time: 7min read
39 1
A A
40
SHARES
4k
VIEWS
Share on FacebookShare on Twitter
ADVERTISEMENT

An ArrayList is a Resizable-array implementation of the List interface.

This class is one of the most commonly used collection in the java environment. It’s so flexible and easy to use and powerful. It’s power and flexibility come from the fact that ArrayList implements all optional list operations, and permits all elements, including null.

Internally an ArrayList utilizes an Array to store it’s items. Because of this some developers usually refer to an ArrayList as a dynamic array.

Hence the ArrayList class provides methods to manipulate the size of the array that is used internally to store the list.

The ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

While using an ArrayList keep the following in mind for the sake of performance:

  1. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  2. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  3. All of the other operations run in linear time (roughly speaking).
  4. The constant factor is low compared to that for the LinkedList implementation.

When you instantiate an ArrayList, you get access to the ArrayList capacity for that instance. This capacity is the size of the array used to store the elements in the list. The ArrayList is always at least as large as the list size.

Then as you add more elements to an ArrayList, its capacity grows automatically. Adding an element to an ArrayList has constant amortized time cost.

You can increases your ArrayList capacity using the ensureCapacity operation. This may reduce the amount of incremental reallocation and can be useful before adding a large number of elements.

An ArrayList is a Resizable-array implementation of the List interface.

This class is one of the most commonly used collection in the java environment. It’s so flexible and easy to use and powerful. It’s power and flexibility come from the fact that ArrayList implements all optional list operations, and permits all elements, including null.

Internally an ArrayList utilizes an Array to store it’s items. Because of this some developers usually refer to an ArrayList as a dynamic array.

Hence the ArrayList class provides methods to manipulate the size of the array that is used internally to store the list.

The ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

While using an ArrayList keep the following in mind for the sake of performance:

  1. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  2. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  3. All of the other operations run in linear time (roughly speaking).
  4. The constant factor is low compared to that for the LinkedList implementation.

When you instantiate an ArrayList, you get access to the ArrayList capacity for that instance. This capacity is the size of the array used to store the elements in the list. The ArrayList is always at least as large as the list size.

Then as you add more elements to an ArrayList, its capacity grows automatically. Adding an element to an ArrayList has constant amortized time cost.

You can increases your ArrayList capacity using the ensureCapacity operation. This may reduce the amount of incremental reallocation and can be useful before adding a large number of elements.


ArrayList API Definition

An ArrayList as a class derives from the AbstractList<E> and implements the following three interfaces:

  1. List<E> – an interface representing an ordered collection
  2. RandomAccess – Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
  3. Cloneable – A class implements the Cloneable interface to indicate to the clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
  4. Serializable – An interface that allows it’s implementers to be serialized and deserialized.
1
public class ArrayList extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Here’s the inheritance hierarchy for an ArrayList:
1
2
3
4
5
 
java.lang.Object
   ↳    java.util.AbstractCollection<E>
       ↳    java.util.AbstractList<E>
           ↳    java.util.ArrayList<E>

3 ways of Instantiating an ArrayList

The ArrayList class provides us three constructors that allow us instantiate an ArrayList:

  1. ArrayList() – Constructs an empty list with an initial capacity of ten.
    This is the most commonly used in many examples.

Here’s one:

1
ArrayList<String> languages=new ArrayList<>();

Find complete android example here.

  1. ArrayList(int initialCapacity) – Constructs an empty list with the specified initial capacity.
  2. ArrayList(Collection<? extends E> c) – Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

4 ways of Adding Data to an ArrayList.

The essence of having a data structure like an a arraylist is for it to hold some lists of data. Those data have to be added.

Defined in the AbstractList which is the parent of the ArrayList class are a couple of add methods which we can use depending on our requirements.

  1. boolean add(E element) – You pass an element as a parameter and it gets appended to the end of the list.

For example let’s say we have an arraylist named languages which should us programming languages:

1
2
3
4
        languages.add("Java");
        languages.add("C#");
        languages.add("VB.NET");
        languages.add("PHP");

In the above case we are adding String objects. Find complete android example here.

However we can also add custom objects. Assuming we have an ArrayList named people to hold a list of human being names:

1
2
3
4
5
6
            Person p=new Person();
            p.setName("Mike");
            people.add(p.getName());
            p=new Person();
            p.setName("John");
            people.add(p.getName());

Find full example here

  1. void add(int index, E element) – Inserts the specified element at the specified position in this list.
  2. boolean addAll(Collection<? extends E> c) – Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
1
2
3
4
5
6
7
8
9
10
11
private ArrayList<Song> getSongList(@NonNull List<Playlist> playlists) {
    final ArrayList<Song> songs = new ArrayList<>();
    for (Playlist playlist : playlists) {
        if (playlist instanceof AbsCustomPlaylist) {
            songs.addAll(((AbsCustomPlaylist) playlist).getSongs(activity));
        } else {
            songs.addAll(PlaylistSongLoader.getPlaylistSongList(activity, playlist.id));
        }
    }
    return songs;
}
Here’s another example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
 
        ArrayList<Integer> al = new ArrayList<Integer>();
 
        for(int i=0; i<5f; i++) {
            al.add(i);
        }
        al.forEach(p -> { System.out.print(p+","); });
        System.out.println();
 
        al.addAll(al);
        al.forEach(p -> { System.out.print(p+","); });
 
}
  1. boolean addAll(int index, Collection<? extends E> c) – Inserts all of the elements in the specified collection into this list, starting at the specified position.

Sorting an ArrayList

Here’s an example:

1
2
3
4
5
6
private void sortPresentations() {
    final ArrayList<Component> sortedComponentList = new ArrayList<>();
    componentPresentationMap.keySet().forEach(sortedComponentList::add);
    sortedComponentList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    sortedComponentList.forEach(component -> componentPresentationMap.get(component).toFront());
}

Top ArrayList Quick Example Snippets

(a). How to Populate an ArrayList from Database

First we create a PreparedStatement with our SQL select statement:

1
        PreparedStatement ps = connection.prepareStatement("select * from lab");

Then invoke the executeQuery() method of the prepareStatement class, thus returing us a result set which we hold in a ResultSet object.

1
        ResultSet rs = ps.executeQuery();

Then we instantiate our ArrayList to hold our data. Then loop through the ResultSet using a while loop and the next() method, filling our ArrayList and returning it outside our loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ArrayList<Lab> getLab() {
    try {
        PreparedStatement ps = connection.prepareStatement("select * from lab");
        ResultSet rs = ps.executeQuery();
        ArrayList<Lab> labs = new ArrayList<Lab>();
        while (rs.next()) {
            Lab lab = new Lab(rs.getInt("labId"), rs.getString("labName"), rs.getString("testFor"),rs.getString("labResult"),
                    rs.getString("reportFile"),rs.getInt("itemId"),getDoctor(rs.getInt("doctorId")));
            labs.add(lab);
        }
        return labs;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

(b). How to Sort an ArrayList and ListView using Comparator in Java

Let’s assume we have a User object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class User
{
    private String name;
    private Float score;
 
    public User(String name,Float score)
    {
        this.name = name;
        this.score = score;
    }
 
    public String getName()
    {
        return this.name;
    }
 
    public Float getScore()
    {
        return this.score;
    }
    @Override
    public String toString()
    {
        return this.name + ": " + Float.toString(this.score) + " wpm";
    }
}

And want to sort our ArrayList of users. Each as you can see from the above has a name and a score, which is a Floating Point number.

Now we want to sort those users according to their scores and show the result in a ListView in android.

SimilarPosts

Java Iterator

Java Iterator

2 years ago
4k
Java Iterable Interface

Java Iterable Interface

2 years ago
4k
Java Control Structures – Loops Introduction

Java Control Structures – Loops Introduction

2 years ago
4k
Java Operators – Logical Operators

Java Operators – Logical Operators

2 years ago
4k

Then our activity will be like this. Needless to say you need to specify imports and create a layout for your project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Highscores_Standard extends AppCompatActivity
{
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTitle(Game.TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_highscores__standard);
 
        ArrayList<String> userNames = Game.readFile(Highscores_Standard.this,Game.USERSFILENAME);
        ArrayList<String> userScores = Game.readFile(Highscores_Standard.this,Game.SCORESFILENAME);
 
        ArrayList<User> users = new ArrayList<User>();
 
        for (int x = 0; x < userNames.size(); x++)
        {
            users.add(new User(userNames.get(x),Float.parseFloat(userScores.get(x))));
        }
 
        users.sort(Comparator.comparing(User::getScore));
        Collections.reverse(users);
 
        ListView listView = (ListView) findViewById(R.id.listBox);
        ArrayAdapter<User> arrayAdapter = new ArrayAdapter<User>(this,android.R.layout.simple_list_item_1,users);
        listView.setAdapter(arrayAdapter);
 
    }
}

In the above we are assuming that we are reading the usernames and their game scores from the filesystem into our arraylist. You may just use dummy data or fetch data from database.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
Share16Tweet10Send
ADVERTISEMENT

Related Posts

Java Iterator
Java

Java Iterator

December 19, 2020
4k
Java Iterable Interface
Java

Java Iterable Interface

December 19, 2020
4k
Java Control Structures – Loops Introduction
Java

Java Control Structures – Loops Introduction

December 19, 2020
4k
Java Operators – Logical Operators
Java

Java Operators – Logical Operators

December 19, 2020
4k
Java Operators – Relational Operators
Java

Java Operators – Relational Operators

December 19, 2020
4k
Java URI
Java

Java URI

December 19, 2020
4k
ADVERTISEMENT

Get Free Projects

  • Home
  • Android
  • Buy Projects
  • My Account

© 2021 Camposha

No Result
View All Result
  • Account
  • Activate
  • Activity
  • Become a Teacher
  • Become a Teacher
  • Become a Teacher
  • Become instructor
  • Blog
  • Blog
  • Cancel Payment
  • Cancel Payment
  • Cart
  • Change Password
  • Change Password
  • Checkout
  • Checkout
  • Checkout
  • Contact
  • Contact
  • Contact Us
  • Content restricted
  • Course Checkout
  • Dashboard
  • Edit Profile
  • Edit Profile
  • FAQs
  • Forgot Password
  • Forgot Password
  • Guest
  • Guest
  • Home
  • Home
  • Home Light
  • Instructor Dashboard
  • Instructor Registration
  • IUMP – Account Page
  • IUMP – Default Redirect Page
  • IUMP – Login
  • IUMP – LogOut
  • IUMP – Register
  • IUMP – Reset Password
  • IUMP – TOS Page
  • IUMP – Visitor Inside User Page
  • List courses
  • List wish list
  • Login
  • Login
  • Maintenance
  • Members
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Plans
  • My Account
  • OnePage Documentation
  • Portfolio Grid
  • Portfolio Masonry
  • Portfolio Multigrid
  • Privacy Policy
  • Products
  • Profile
  • Profile
  • Profile
  • Projects
  • Register
  • Register
  • Register
  • Register
  • Sample Page
  • Shop
  • Sign in
  • Sign up
  • Student profile
  • Student Registration
  • Thank You
  • Thank You

© 2021 Camposha

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In