简体   繁体   English

用更多列替换Arraylist

[英]Replace in a Arraylist with more Columns

So for an assignment i need to to replace an Element in an ArrayList. 因此,对于分配,我需要替换ArrayList中的Element。 As an example i have a Team Class 例如,我有一个团队班

class Team {
  int id, int points;
  String name;
}

I need to find the ID of the Team in the List and replace the Points with new Points. 我需要在列表中找到团队的ID,然后用新的积分替换积分。 I know i can get the index of the ID with list.get(i).id but i don't know how to replace the Points there. 我知道我可以使用list.get(i).id获取ID的索引,但是我不知道如何替换那里的Points。 I know that there is a list.set() command but i didn't find how to replace the Points of the Team in the ArrayList because the set Command doesn't accept "i" as a Parameter. 我知道有一个list.set()命令,但是我没有找到如何替换ArrayList中团队的积分,因为set命令不接受“ i”作为参数。 Already thanks in advance 已经提前谢谢

I suppose you have an ArrayList of Team objects and you want to change the points of a team with a specific id? 我想您有一个Team对象的ArrayList,并且您想更改具有特定ID的团队的积分吗?

In order to do this, you can do: 为此,您可以执行以下操作:

for(int i = 0; i < yourlist.size(); i++)
 if (yourlist.get(i).id == yourID)
    yourlist.get(i).points += 1;
    break;

Each element of the list will be a Team . 列表中的每个元素都是一个Team As you said, first you need to get the element Team that has the ID of the Team you want to change the points of. 如您所说,首先您需要获取具有要更改其积分的Team ID的元素Team To do this, you need to somehow iterate over the list and find that such element(s). 为此,您需要以某种方式遍历列表并找到此类元素。 Watch out, as List<T>.Get(int i) will give the element present at index i of the list, not the Team with ID i . 注意,因为List<T>.Get(int i)将给出存在于列表索引i的元素,而不是ID为iTeam Then, to set the points of the Team , either assign a value directly, or, better yet, define and use setter methods. 然后,要设置Team的要点,可以直接分配一个值,或者更好的是定义和使用setter方法。 List<T>.Set(int i, T elem) replaces the Team at index i , for the Team elem , so it shouldn't be what you want to be doing, as points , the thing you want to change, can be changed directly on the instance already present in the list. List<T>.Set(int i, T elem)取代了Team在索引i ,为Team elem ,所以它不应该是你想要做的,是什么points ,你想改变的东西,可以直接在列表中已经存在的实例上更改。 To use Set , you'd have to create a new Team instance with a new value for points . 要使用Set ,您必须创建一个新的Team实例,并用一个新的points值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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