简体   繁体   中英

Accessing elments from ArrayList

I've learnt how to Create an Arraylist of Objects , such arrays are dynamic in nature. eg 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) ?

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.

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

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.

Matrices m = list.get(1)

请阅读Java文档

You can get Matrices object from list as:

 Matrices m = list.get(0);// fist element in list
 m.anyPublicMethod();
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM