I have list as example below
val mylist : List<Class> = (Class(foo,1),Class(bar,2))
I know value 1
is coming to me but How can i get foo
value in list?
Thanks
The following structure would probably work:
// This gets the first object of the class "Class" in your list. (First index)
Class classVariable = mylist.get(0);
// Now that you have an object of type Class, you can retrieve the value of foo // using whatever property you just used in the constructor
Type foo = classVariable.foo;
If you want to do it in one line:
VariableType foo = myList.get(0).foo
// OR
VariableType foo = myList.get(0).getFoo(); // if your class member "foo" is private access.
In response to the comment below this answer:
// NOTE: THIS CODE WILL NOT COMPILE. These are two separate snippets that
// you will have to place in the correct positions
// Class used in example:
public class Class {
public String foo; // public so we don't have to use get() set()
public Integer value;
// constructor
public Class(String foo, Integer value) {
this.foo = foo;
this.value = value;
}
}
// For loop to find the value of foo if we know a given value:
for (int i = 0; i < mylist.size(); i++) {
// Gets an object at each index in list.
Class object = mylist.get(i);
if (object.value == <INSERT VALUE THAT YOU ARE LOOKING FOR>) {
return object.foo; // this will get the value for foo
// based on the other value that you know
}
}
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.