是否可以打印出放在数组列表中的对象的实例变量的某些值?吸气剂?

时间:2018-04-19 06:57:16

标签: java

我创建了6个大学对象,我将其添加到大学对象的ArrayList中。我能够打印每个对象没问题。我想知道是否可以打印出对象的某些实例变量(在这种情况下是名称)我尝试以不同的方式使用getter方法,但是出现了错误。任何建议都会有所帮助,谢谢!附:在大学课堂上宣布时,在底部的方法是不起作用的?为什么呢?

import java.util.ArrayList ;

public class TheArrayList

{

    public static void main(String[] args)
{

        ArrayList<College> schoolList = new ArrayList<College>(3);

        College schoolOne = new College("Palomar", "San Marcos", 26000, 1943) ;
        College schoolTwo = new College("Mira Costa", "Oceanside", 19000, 1934) ;
        College schoolThree = new College("Grossmont", "El Cajon", 18000, 1968) ;
        College schoolFour = new College("SaddleBack", "Mission Viejo", 26000, 1934) ;
        College schoolFive = new College("Mesa", "San Diego", 25000, 1958) ;
        College schoolSix = new College("Southwestern", "Chula Vista", 27000, 1961) ;



        schoolList.add(schoolOne) ;
        schoolList.add(schoolTwo) ;
        schoolList.add(schoolThree) ;
        schoolList.add(1, schoolFour) ;
        schoolList.add(2, schoolFive) ;


        showSchools(schoolList) ;

    }
//Method in The Array List
    private static void showSchools(ArrayList<College> list){
        System.out.println(list) ;
    }


}




    public class College
{
    private String name = "" ;
    private String city = "" ;
    private int students = 0 ;
    private int established = 1900 ;

        public College(String name, String city, int students, int established){
            this.name = name ;
            this.city = city ;
            this.students = students ;
            this.established = established ;

        }

//Getters
    public String getName(){
        return name ;
    }

    public String getCity(){
        return city ;
    }

    public int getStudents(){
        return students ; 
    }

    public int getestablished(){
        return established ;
    }
//Setters
    public void setName(String newName){
        name = newName ;
    }

    public void setCity(String newCity){
        city = newCity ;
    }

    public void setStudents(int newStudents){
        students = newStudents ;
    }

    public void setEstablished(int newEstablished ){
        established = newEstablished ;
    }

    public String toString() {
        return name + " " + city + " " + students + " " + established ; 
    } 
}

0 个答案:

没有答案