如何显示对象的arraylist?

时间:2015-10-23 21:46:05

标签: java arraylist

我写了一个代码,它从一个txt文件中取一行,将它分成不同的字符串和整数,然后将它作为一个名为教授的对象存储到数组列表中。主类的代码如下:

public class Main {

    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("text.txt");
        BufferedReader reader = new BufferedReader(file);
        ArrayList<Profesor>professors = new ArrayList<Profesor>();
        String line = reader.readLine();
        String[] lineSplit = new String[11];

        while(line != null){
            lineSplit = line.split("\\s+");
            professors.add(new Profesor(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[3]), Integer.parseInt(lineSplit[4]), Integer.parseInt(lineSplit[5]), Integer.parseInt(lineSplit[6]), Integer.parseInt(lineSplit[7]), Integer.parseInt(lineSplit[8]), Integer.parseInt(lineSplit[9]), Integer.parseInt(lineSplit[10]), Integer.parseInt(lineSplit[11])));                     
        }

    }

}

Profesor课程:

public class Profesor {
    private String name;
    private String subject;
    private int wh0;
    private int wh1;
    private int wh2;
    private int wh3;
    private int wh4;
    private int wh5;
    private int wh6;
    private int wh7;
    private int wh8;
    private int wh9;    
    public Profesor(String n, String s, int w0, int w1, int w2, int w3, int w4, int w5, int w6, int w7, int w8, int w9){
        name = n;
        subject = s;
        wh0 = w0;
        wh1 = w1;
        wh2 = w2;
        wh3 = w3;
        wh4 = w4;
        wh5 = w5;       
        wh6 = w6;
        wh7 = w7;
        wh8 = w8;
        wh9 = w9;               
    }
}

和txt文件类似:

Jhon Maths 173 486 789 954 684 235 446 168 749 851   
Robert MathsII 283 686 948 978 144 224 473 468 778 845

问题是如何在控制台中显示arraylist? 以及如何访问arraylist中的一个对象内的字符串?
提前致谢

2 个答案:

答案 0 :(得分:0)

您可以为每个get()使用ArrayList方法。因此,输入professors.get(0)将返回第一个Professor对象。

不仅如此,一旦获得该对象,您需要创建名为getNamegetObject的内容。这是因为你的变量是私有的,而教授之外的类正试图访问私有变量。

它看起来像这样:

public String getName() {
    return name;
}

一旦你在Professor课程中使用了这个方法,你可以通过调用

在你的Main课程中调用它
Profesor p = professors.get(0);   // returns the first Profesor inside professors ArrayList
String professorName = p.getName();   // returns the name variable of the above professor

有关ArrayList的更多信息,请点击此处:

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)

答案 1 :(得分:0)

这就是:当你尝试打印一个对象时,Java通过调用对象的toString()函数来计算要打印的内容。因此,您需要通过在教授对象中实现该特定函数来告诉Java:

public String toString()
{
    return name + subject + Arrays.toString(wh); 
    // put all those wh numbers into an array!

}

此函数返回以下形式的字符串:

Jhon Maths 173 [486, 789, 954, 684, 235, 446, 168, 749, 851]这是Java打印出来的。

现在,您可以遍历ArrayList名教授,只需逐句System.out.println