从数组转换为arrayList

时间:2013-09-04 18:44:58

标签: java arrays arraylist

好吧,这个代码是我所拥有的赋值的一部分,我将实现一个equals()方法来检查两条线是否相等,如果两个端点相同,则将两条线定义为相等。但是我无法检查它,因为当我按原样运行程序时,它的空白就好像数组列表为空。我的问题是:我是否需要通过文件更改循环读取,或者是否需要取消注释初始数组并对arrayList执行某些操作?

任何帮助都会非常感激!!

    //Line[] lines;

    ArrayList<Line> lines;     
    Scanner reader;

public MyDrawing()

    super();

    this.setPreferredSize(new Dimension(500,500));
}

/**
 *  Reads the file and builds an array of Line objects.
 *  
 * @param fileName The name of the file that contains the lines
 * @throws Exception
 */
public void read( File fileName ) throws Exception
{
    reader = new Scanner(fileName);

    //----------------
    // Change to Arraylist. Make the name of the arraylist "lines" so that code      in paintComponent works.
    //---------------------
    //Have to read the first number before starting the loop
    int numLines = reader.nextInt();
    //lines = new Line[numLines];
    ArrayList<Line>lines = new ArrayList<Line>();

这里我实例化了arrayList

    //This loop adds a new Line object to the lines array for every line in the file read.
    while( reader.hasNext() ) {
        for( int i = 0; i < numLines; i++ ) {
            int x = reader.nextInt();
            int y = reader.nextInt();
            Point beg = new Point(x,y);
            x = reader.nextInt();
            y = reader.nextInt();
            Point end = new Point(x,y);

            String color = reader.next();

            Line l =  new Line( beg, end, color );

            //----------------
            // Change to make sure that you only add lines that don't already exist.
            //--------------------
            lines.add(l);
            //lines[i] = l;

在这里我尝试将行“l”添加到列表中             }

}


    if( lines != null ) {
        for( Line l: lines ) {
            int x1 = l.getBeg().getX();
            int y1 = l.getBeg().getY();
            int x2 = l.getEnd().getX();
            int y2 = l.getEnd().getY();

            g.setColor(l.color);
            g.drawLine(x1, y1, x2, y2);

            System.out.println(l);
        } 
    }
    //Print the action to the console
    System.out.println( "drawing lines" );
}

}

1 个答案:

答案 0 :(得分:0)

您有一个名为lines的实例变量,但您没有在read方法中使用它。在read方法中,您声明了一个具有相同名称lines的局部变量并读入它,但是没有更改具有相同名称的实例字段。因此,当您尝试使用它时,该实例字段将为null。很遗憾,您使用if(lines != null)保护代码,而不是问自己为什么某些内容null不应该。

虽然迭代实例字段的代码无论lines是数组还是ArrayList,但是您的代码读入它都无法使用数组,因为数组没有{ {1}}方法。因此,在将实例变量更改为数组时,read方法仍然编译的事实会为您提示它不使用该数组。

将读取方法中的行add更改为ArrayList<Line>lines = new ArrayList<Line>();。然后,您正在读入的列表将存储在稍后使用的实例字段中。当然,如果将lines = new ArrayList<Line>();声明为数组,它将不再编译。