3 回答

TA貢獻1829條經驗 獲得超7個贊
聽起來您想將汽車的信息打印為字符串。在這種情況下,您需要覆蓋 CarPartsDto 類中的 toString() 方法。
@Override
public String toString() {
return "Manufacturer: " + manufacturer + "\n" +
"Type: " + type + ",\n" +
"Colour: " + colour + ",\n" +
"Torque: " + torque + ",\n" +
"MaxSpeed: " + maxSpeed;
}
要調用它,您只需要在不使用任何方法或使用 toString 方法的情況下調用您的對象。
for (CarPartDto car : cars) {
System.out.println(car);
}
此外,如果您需要任何其他形式的信息,您也可以編寫自己的方法并以您需要的任何格式返回它(在本例中為字符串):
public String returnCarInfo(){
return "Type: " + type + ",\n" +
"Colour: " + colour + ",\n" +
"Torque: " + torque + ",\n" +
"MaxSpeed: " + maxSpeed + ",\n" +
"Manufacturer: " + manufacturer;
}
并使用該方法調用它。
System.out.println(car.returnCarInfo());
希望這可以幫助!

TA貢獻1829條經驗 獲得超4個贊
我不能發表評論,所以:
看起來您想訂購類型只是簡單地將您的課程更改為
public class CarPartDto {
public String manufacturer;
public String type;
public String colour;
public Long torque;
public Long maxSpeed;
}
或者你可以創建一個方法(在你的類中)而不是返回你想要的格式對象:
public String getCarInfo(){
return "manufacturer: " + manufacturer + "\ntype: " + type + "\ncolour: "+colour + "\ntorque: " + torque + "\nmaxSpeed: " + maxSpeed;
}

TA貢獻1864條經驗 獲得超2個贊
僅回答標題,Java - 我們如何使集合中的某個對象在索引 0 處返回;
Sets 通常沒有將用戶友好的順序作為設計目標,盡管某些實現確實有:TreeSet按自然順序LinkedHashSet返回其元素,按插入順序返回其元素。
你可以用一個簡單的代碼試試
Random r=new Random();
Set<Integer> treeset=new TreeSet<Integer>();
Set<Integer> linked=new LinkedHashSet<Integer>();
Set<Integer> simple=new HashSet<Integer>();
for(int i=0;i<10;i++){
int n=r.nextInt(100);
System.out.print(n+", ");
treeset.add(n);
linked.add(n);
simple.add(n);
}
System.out.println();
for(Object i:treeset.toArray())
System.out.print(i+", ");
System.out.println();
for(Object i:linked.toArray())
System.out.print(i+", ");
for(Object i:simple.toArray())
System.out.print(i+", ");
(https://ideone.com/Wz3o61 - 第一行是一堆隨機數,第二行是TreeSet,有序,第三行是LinkedHashSet,保留輸入順序,最后一行是HashSet,具有任意順序)。
因此,如果您的問題與Set-s 有關(在撰寫本文時似乎并非如此),您可以通過首先使用LinkedHashSet和添加該元素來強制執行“第一個”元素,或者選擇一種更深奧的方法/創建具有合適順序的元素類 - 也許使用枚舉。但問題更可能與打印對象有關,toString()即代碼中某處的 like 方法。
添加回答
舉報