[英]Java - ArrayList<E> Parameter in function
I wanted to use a function that used a arraylist for multiple types of arraylists, but I don't know how to do that. 我想使用将arraylist用于多种类型的arraylist的函数,但是我不知道该怎么做。
ArrayList<TextView> List2 = new ArrayList<>();
ArrayList<View> List1 = new ArrayList<>();
ChangeTextSize(List1);
ChangeTextSize(List2);
public void ChangeTextSize(ArrayList List){
for (int i = 0; i < List.size(); i++){
List.get(i).setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
}
}
-Edit: The function is meant for any view. -编辑:该功能适用于任何视图。 I'm now aware that setTextSize isn't allowed for view. 我现在知道setTextSize不允许查看。
If you want to change the text size using the function setTextSize
the object which you call the function on has to be a TextView
because that object has the function . 如果要使用setTextSize
函数更改文本大小,则调用该函数的对象必须是TextView
因为该对象具有函数 。 A View
doesn't have the function setTextSize
so that won't work. View
不具有setTextSize
函数,因此无法使用。
But if you have a function that both TextView
and View
have; 但是,如果您拥有TextView
和View
都具有的功能; for example setBackgroundColor
you can do it like this: 例如setBackgroundColor
您可以这样做:
public void changeBackgroundColor(ArrayList<? extends View> list) {
for (View v: list) {
v.setBackgroundColor(Color.red);
}
}
So basically you give your list
argument a generic; 因此,基本上,您为list
参数指定了通用名称; meaning in this case: "all the element in the list should be a view or sub-class thereof". 在这种情况下的含义是:“列表中的所有元素都应该是视图或其子类”。 So the methods you can call on the element from this list are all methods available in the View
class. 因此,您可以在此列表中调用元素的方法是View
类中可用的所有方法。
But if you want to change text-sizes your function needs to accept a list of TextView
(or sub-classes thereof), like this: 但是,如果要更改文本大小,则函数需要接受TextView
(或其子类)列表,如下所示:
public void changeTextSize(ArrayList<? extends TextView> list) {
for (TextView tv: list) {
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
}
}
Is this Android? 这是Android吗?
You can use a wild card to allow a range of type-parameters. 您可以使用通配符来允许一定范围的类型参数。 Something like: 就像是:
public void ChangeTextSize(ArrayList<? extends TextView> list){
for (int i = 0; i < list.size(); i++){
list.get(i).setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
}
}
But I don't see that View
has a method setTextSize
so obviously that type can't be used here. 但是我没有看到View
有一个setTextSize
方法,因此显然不能在这里使用该类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.