简体   繁体   中英

Replace in a Arraylist with more Columns

So for an assignment i need to to replace an Element in an ArrayList. 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. 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. 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. 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?

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 . 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. 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 . Then, to set the points of the Team , either assign a value directly, or, better yet, define and use setter methods. 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. To use Set , you'd have to create a new Team instance with a new value for points .

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