我有一个包含Objects的ArrayList。我一直想要/需要做的是在ArrayList中搜索一个特定的对象,如果找到则改变其中一个值。 I.E.我有一队足球运动员,说费城老鹰队包含球队名称,得分总计得分,然后按名字,姓氏,比赛和位置列出所有球员。我正在寻找一个特定的球员,说Chad Hall,我想把他从老鹰队中移除并将他交易给新英格兰爱国者队。到目前为止我所拥有的是ArrayList的迭代,但是我的代码没有找到播放器然后退出。
case 6:
String name = "";
System.out.print("Who would you like to trade? ");
name = kb.nextLine();
tradePlayer(nflTeams, name);
public static void tradePlayer(ArrayList<Team> nflTeams, String name)
{
Scanner kb = new Scanner(System.in);
String teamName = "";
System.out.print("What team do you want to trade this player to?(Team Acronym) " );
teamName = kb.nextLine();
for(Team t: nflTeams){
if (nflTeams.contains(name.toLowerCase()))
t.setName(teamName);
}
System.out.println("Cannot find " + name);
}
Player
课程通过名字,姓氏,队伍,位置和比赛来构建球员。我想改变的是团队。在Team
课程中,我有setName(String)
来设置团队名称。
非常感谢任何建议或想法。
答案 0 :(得分:2)
if (nflTeams.contains(name.toLowerCase()))
你想做什么?您的列表nflTeams
包含Team
个对象而非名称
这不起作用。
如果您需要通过其Team
访问name
,请改用Map<String,Team>
答案 1 :(得分:0)
您必须从指定的name
获取团队中的玩家列表并从中删除,如:
String teamToAddNewPlayer = "New England Patriots";
String deletedPlayer = null;
for(Team t: nflTeams){
List<String> players = t.getPlayers();
if (players.contains(name)){
deletedPlayer = players.remove(name);
}
if (t.getName().equals(teamToAddNewPlayer))
players.add(name);
}
if (deletedPlayer == null)
//nothing was deleted
else
//player was deleted
答案 2 :(得分:0)
使用迭代器可以让您更好地控制您正在尝试的内容。
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
此示例来自source