0
我在這裏有問題。我有兩個列表,這兩個列表都有一些共同的元素。 這些常見元素以及值必須放在另一個列表中。這是非常煩人的要求。匹配兩個列表值,最後得到一個具有不同值的最終列表
我的測試類如下:
import java.util.ArrayList;
import java.util.List;
public class Player {
private int singleModeVal;
private int doubleModeVal;
private String mode;
private String name;
public Player(){}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getSingleModeVal(){
return singleModeVal;
}
public void setSingleModeVal(int val1){
this.singleModeVal=val1;
}
public int getDoubleModeVal(){
return doubleModeVal;
}
public void setDoubleModeVal(int val2){
this.doubleModeVal=val2;
}
public String getMode(){
return mode;
}
public void setMode(String mode){
this.mode = mode;
}
public List<Player> getSinglePlayerscoreList(){
List<Player> singlePlayerscoreList = new ArrayList<Player>();
for(int i=0;i<2;i++){
Player player = new Player();
player.setName("A");
player.setMode("singlePlayerMode");
player.setSingleModeVal(100);
player.setDoubleModeVal(200);
singlePlayerscoreList.add(player);
}
return singlePlayerscoreList;
}
public List<Player> getDoublePlayerscoreList(){
List<Player> doublePlayerscoreList = new ArrayList<Player>();
for(int i=0;i<2;i++){
Player player = new Player();
player.setName("B");
player.setMode("doublePlayerMode");
player.setSingleModeVal(300);
player.setDoubleModeVal(400);
doublePlayerscoreList.add(player);
}
return doublePlayerscoreList;
}
}
另一類是:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Tester {
private Player player = new Player();
public static void main(String args[]){
new Tester().showValue();
}
private void showValue(){
List<Player> singlePlayerScore = new ArrayList<Player>();
List<Player> doublePlayerScore = new ArrayList<Player>();
singlePlayerScore = player.getSinglePlayerscoreList();
doublePlayerScore = player.getDoublePlayerscoreList();
List<Player> allScoreList = new ArrayList<Player>();
allScoreList.addAll(singlePlayerScore);
allScoreList.addAll(doublePlayerScore);
How do i iterate here, and print my data as:
Name singlePlayerScore Double Player Score TotalScore
A 100 200 300
B 300 400 700
}
}
}
當我重複我收到了兩次,它的價值和B相同。
有沒有一種有效的方法來執行所需的。
爲什麼你迭代在getSinglePlayerscoreList和getDoublePlayerscoreList循環兩次?這至少是爲什麼你在showValue迭代中得到A和B兩次。 –
您的'Player'類需要'equals()'和'hashCode()' - 如果沒有這些方法,您無法真正使用Collection API。然後查看['List.retainAll()'](http://download.oracle.com/javase/7/docs/api/java/util/List.html#retainAll(java.util.Collection)) –
Player實現可比較的,將啓用:設置 list = new TreeSet (); –