KNU
KNU

Reputation: 2515

Accessing elments from ArrayList

I've learnt how to Create an Arraylist of Objects , such arrays are dynamic in nature. e.g. to create an array of objects(instances of class Matrices ) having 3 fields, the code is like given below :

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

Moreover, the Matrices class goes like this:

public class Matrices{
int x;
int y;
int z;

Matrices(int x,int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}

Now, how can I access each fields of any element from this array name list ? In particular, how to access the 20 field from 2nd element of this array whose value is (1,2,20) ?

Upvotes: 0

Views: 261

Answers (6)

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

You can get Matrices object from list as:

 Matrices m = list.get(0);// fist element in list
 m.anyPublicMethod();

Upvotes: 0

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32458

Matrices element = list.get(1); will do the job. ArrayList is a zero index collection. So list.get(1) will give the 2nd element.

You should check relevant apis, here ArrayList

Upvotes: 1

Laurent B
Laurent B

Reputation: 2220

Matrice m = list.get(1);
int twenty = m.getThirdElement(); // or whatever method you named to get the 3rd element (ie 20);

// in one go :
twenty = list.get(1).getThirdElement();

Upvotes: 0

Sanjeev
Sanjeev

Reputation: 9946

Matrices m = list.get(1)

read java docs please

Upvotes: 0

Georgian
Georgian

Reputation: 8960

I see this as a search algorithm question.

You iterate through the list, and check if the current iteration's element contains the desired values.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499870

You just use the get method:

// 2nd element; Java uses 0-based indexing almost everywhere
Matrices element = list.get(1);

What you do with the Matrices reference afterwards is up to you - you've shown the constructor call, but we don't know whether those values are then exposed as properties or anything else.

In general, when you're using a class you should look at its documentation - in this case the documentation for ArrayList. Look down the list of methods, trying to find something that matches what you're trying to do.

You should also read the tutorial on collections for more information about the collections library in Java.

Upvotes: 8

Related Questions