public static void main(String[] args) {
/*The following is the code to a Class containing two elements, name and boardFootage. I'll get the data from a Scanner, store it in an ArrayList in my Furniture object, then print out the items of the ArrayList in ascending order.
*/
class Furniture implements Comparable<Furniture> {
public String toString() {
return getName() + ": " + getBoardFootage() + "\n";
}
private String name;
private double boardFootage;
Furniture() {
name = "";
boardFootage = 0.0;
}
Furniture(String nameInput, double boardFootageInput) {
name = nameInput;
boardFootage = boardFootageInput;
}
public String getName()
{
Scanner keyboard = new Scanner(System.in);
String name = "";
while (!name.equalsIgnoreCase("quit"))
{
name = keyboard.next();
if (name == "quit") {
System.out.println("Project Summary");
// PRINT LIST SORTED BY PROJECT SIZE FROM SMALLEST
// TO LARGEST USING Collections.sort METHOD
}
}
return name;
}
public void setName(String name) {
Scanner keyboard = new Scanner(System.in);
this.name = keyboard.next();
}
public double getBoardFootage() {
Scanner keyboard = new Scanner(System.in);
double boardFootage = 0.0;
boardFootage = keyboard.nextDouble();
return boardFootage;
}
public void setBoardFootage(double boardFottage) {
Scanner keyboard = new Scanner(System.in);
this.boardFootage = keyboard.nextDouble();
}
public int compareTo(Furniture o) {
if (this.boardFootage < o.boardFootage) {
return -1;
} else if (this.boardFootage > o.boardFootage) {
return 1;
}
return this.name.compareTo(o.name);
}
}
Furniture furniture = new Furniture();
ArrayList<Furniture> furnitureList = new ArrayList<Furniture>();
答案 0 :(得分:1)
你随时可以的方式?
//furnitureRef is a reference to a member of the list
for( Furniture furnitureRef : furnitureList ) {
//Do stuff with furnitureRef
}
这看起来像是一个家庭作业问题,所以我很谨慎,如果没有你至少尝试自己做一些事情就给予更多帮助。
此外,通常接受的方法是为您定义的每个对象创建一个toString方法。这个toString函数应该返回一个对象的字符串,序列化,如:
class Car {
String make;
String model;
public String toString() {
return "{ make: " + make + " model: "+model+" }";
}
}
这将允许你写:
//furnitureRef is a reference to a member of the list
for( Furniture furnitureRef : furnitureList ) {
System.out.println( furnitureRef.toString() );
}