package com;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionDemo {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Person("张三", 13, "北京"));
list.add(new Person("李四", 8, "上海"));
}
}
请问为什么用list.add添加会有错?怎么改?错误提示是:构造函数 Person(String, int, String)未定义什么意思?
public class People{
private String name;
private int age;
private String city;
public People(){
}
public People(String name,int age,String city){
this.name=name;
this.age=age;
this.city=city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Person 里面添加这个构造函数啊
楼上答案可以,创建Person类 同时构造函数,封装私有属性
Person类里面缺少带有String, int, String着三个参数的构造函数;
在Person类里加上这个构造函数就行了
public Person(String name, int age, String city){
//你自己的操作
}
public People(String name,int age,String city){
this.name=name;
this.age=age;
this.city=city;
}
没有定义该构造函数
创建Person类 同时构造函数,封装私有属性
错误不在list集合的add方法[list.add],而是使用new关键字实例化Person对象时出现了错误,只要在Person类内添加对应的构造方法即可。