gpt4 book ai didi

java - Java 中的打印列表

转载 作者:行者123 更新时间:2023-12-02 01:49:55 27 4
gpt4 key购买 nike

我是 Java 新手。我不确定为什么 my2.print_list(); 行仅打印对象 my2。我想每次打印整个对象列表。我将每个对象添加到构造函数中列出。我 90% 确信函数 print_list 中的 for 循环是好的。编译器显示没有问题。我将感谢所有帮助。

public class Main {

public static void main(String[] args) {
// write your code here
rectangle my = new rectangle(5);
rectangle my1 = new rectangle(3,6);
rectangle my2 = new rectangle(10,7);

System.out.println( my2.getCounter());
my2.print_list(); ////////////////////<- described line

}
}

///我的类(class)矩形

    import java.util.ArrayList;
import java.util.List;

public class rectangle {
public static int counter =0;
public int x;
public int y;
public List<rectangle> List = new ArrayList<rectangle>();

public rectangle(int x, int y) {
this.x = x;
this.y = y;
System.out.println("Rec");
List.add(this);
counter++;
}
public rectangle(int x) {
this.x = x;
this.y = x;
System.out.println("Sqr");
List.add(this);
counter++;
}

@Override
public String toString() {
return "x->"+x+" y->"+y+" Field: "+(x*y);
}

public void print_list()
{
for(rectangle x : List)
{
System.out.println(x);
}
}

最佳答案

类的每个实例都有其自己的List实例。如果需要共享,请将其设为静态(这是填充List 的唯一方式)。另外,请重命名变量List(它看起来完全类似于接口(interface)java.util.List)。此外,没有理由将其公开。

private static List<rectangle> myList = new ArrayList<rectangle>();

然后更改print_list,例如

public void printList()
{
for(rectangle x : myList)
{
System.out.println(x);
}
}

此外,类名称应为 Rectangle(遵循 Java 命名约定)。

关于java - Java 中的打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53134163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com