问题
Lets assume that I store values to List A, List B & List C through for loop. List A,B,C values is added by the following way:
for (int j = 0; j <5; j++)
{
list_A.add("Value"+i);
list_B.add("Value"+i);
list_C.add("Value"+i);
}
To access the List out of the method I'm using this keyword by the following way:
private CharSequence ListA[]; // declaration
this.ListA= list_A.toArray(new CharSequence[list_A.size()]); //accessing with this keyword
Now I am adding all these list to another List by the following way
List<List<String>> finallist = new ArrayList<>();
finallist .add(list_A);
finallist .add(list_B);
finallist .add(list_C);
I did some searching but I couldn't find how to declare and access List< List< String>> using this keyword?
Note: It is the actual modification of the question that I have asked here. As I couldn't get any answer, I thought I could make it bit simple and have raised the question here.
回答1:
You use the this keyword to access a member of method of the current instance of the class. You would only do that inside of a function- because outside of a function the this keyword isn't defined.
Generally you don't actually use this.variable or this.method. You only need to do that if another variable at overriding scope uses the same name. Generally you see this in autogenerated setters/constructors and not much else- its easier just not to reuse the name.
回答2:
You need to display your code, because the scopes really matter in this case. Whether or not you need the this keyword is highly dependent on where things are declared.
回答3:
this.ListA
means that you want to access field ListA
of this
object.
If you declare a variable as List<List<String>> finallist = new ArrayList<>();
inside some method, then it is not a field of this
object, and you can't access it with this
keyword. If you want to access it outside the method, you should declare it as a class field.
It is Java-very-basics thing about classes, fields and this
. You should learn Java very basics to eliminate hundreds of questions like this, on which you will loose a lot of time. Much more than to learn very basics.
回答4:
When accessing a variable of one class in another, you could do something like this:
Main Class
public static final List<String> list_A = new ArrayList<>();
static{
for (int j = 0; j <5; j++)
{
list_A.add("Value"+i);
}
}
Fragment Class
CharSequence ListA[];
ListA = MainClass.list_A.toArray(new CharSequence[MainClass.list_A.size()]);
I would recommend using the static
keyword in the declaration of list_A
来源:https://stackoverflow.com/questions/42152389/access-listliststring-using-this-keyword