我有一个POJO类,其中一个String
数组属性的大小为2.但是我创建了Person
类的对象,并传递了大小为5的数组。它没有显示任何异常。为什么呢?
package classObject;
import java.util.Arrays;
public class Person implements Cloneable {
String name;
int age;
String[] skills = new String[2];
Person() {
}
Person(String name, int age, String[] skills) {
this.name = name;
this.age = age;
System.out.println("this.skills.length " + this.skills.length);
System.out.println("skills.length " + skills.length);
this.skills = skills;
System.out.println("Got array is " + Arrays.asList(this.skills));
System.out.println("length of arrays is " + this.skills.length);
}
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;
}
@Override
protected Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
}
// Creating the Object of Person Class
public class classObject {
/* Way to create an object of any class */
public static void main(String args[]) {
try {
// Define the array with len 5
String[] skills = new String[5];
skills[0] = "Java";
skills[1] = "PHP";
skills[2] = "JDBC";
skills[3] = "ORACLE";
skills[4] = "SQL";
// Passing the array
Person objPerson = new Person("Mohit", 27, skills);
System.out.println("Size is " + objPerson.skills.length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
String[]
是一个对象,虽然它看起来不像。所以当你申报时。
String[] skills = new String[2];
您实际上是在声明指向新对象的指针,该对象是String[]
对象,其大小为2
。
然后你来了一个新的String[]
大小为5
的对象,你的引用现在指向那个。
此过程与原始对象无关,因为当您声明:
this.skills = skills;
你没有影响this.skills
指向的对象;只有指针本身。 String[2]
对象没有指向它的指针,垃圾收集器可能会很长并且会破坏它。
答案 1 :(得分:1)
您将类变量指向函数中传递的参数...在构造函数中检查其大小,如果它不是2,则抛出IllegalArgumentExepction。