我正在尝试按区域对形状列表进行排序。我正在使用Iterator在列表中移动并在列表的每个元素上调用Rectangle.calculateArea,但是打印的列表不会输出每个元素的面积。输出是对每个元素的十六进制引用。下面是输出,后跟代码。如何使我的输出显示计算面积?
矩形区域:
矩形@ 15db9742
矩形@ 6d06d69c
矩形@ 7852e922
矩形@ 4e25154f
矩形@ 70dea4e
public class RectangleSortTest {
public static void main (String[] args) {
List<Rectangle> list = new ArrayList<>();
//Create Rectangle ArrayList
list.add(new Rectangle(4, 3));
list.add(new Rectangle(3, 3));
list.add(new Rectangle(4, 4));
list.add(new Rectangle(5, 1));
list.add(new Rectangle(1, 1));
//Add Rectangle elements to Rectangle list
calculateListArea(list);
//Calculates area for each rectangle element
System.out.print("Rectangle Areas:");
printList(list);
//Print rectangle list after area calculation
}
private static void calculateListArea(List<Rectangle> list) {//Calculates Rectangle list areas
ListIterator<Rectangle> iterator = list.listIterator();
while (iterator.hasNext()) {
Rectangle rectangleElement = iterator.next();
Rectangle.calculateArea(rectangleElement.getWidth(), rectangleElement.getHeight());
}
}
private static void printList(List<Rectangle> list) {//Print Rectangle list
for (Rectangle element: list) {
System.out.printf("%n%s", element);
}
}
}
最佳答案
您可以使其简单,如下所示:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RectangleSortTest {
public static void main(String[] args) {
List<Rectangle> list = new ArrayList<Rectangle>();
// Add some rectangle to a list
list.add(new Rectangle(4, 3));
list.add(new Rectangle(3, 3));
list.add(new Rectangle(4, 4));
list.add(new Rectangle(5, 1));
list.add(new Rectangle(1, 1));
// Sort the list on area
Collections.sort(list);
// Print the list
System.out.println("Rectangles in ascending order of areas:");
printList(list);
}
static void printList(List<Rectangle> list) {
for (Rectangle element : list) {
System.out.println(element);
}
}
}
class Rectangle implements Comparable<Rectangle> {
int width, height, area;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}
@Override
public int compareTo(Rectangle rectangle) {
if (this.getArea() > rectangle.getArea())
return 1;
else if (this.getArea() == rectangle.getArea())
return 0;
else
return -1;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + ", area=" + this.getArea() + "]";
}
}
输出:
Rectangles in ascending order of areas:
Rectangle [width=1, height=1, area=1]
Rectangle [width=5, height=1, area=5]
Rectangle [width=3, height=3, area=9]
Rectangle [width=4, height=3, area=12]
Rectangle [width=4, height=4, area=16]
关于java - 使用Iterator调用多参数方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58905051/