java集合问题

Student类代码如下:

import java.util.Arrays;

import java.util.HashSet;

import java.util.Set;


public class Student {

private String id;

private String name;

public Set<Course> courses;

public Student(String id,String name){

this.id=id;

this.name=name;

this.courses = new HashSet<Course>(); 

//等价于HashSet courses = new HashSet(); 

}

public Student(){

this.courses = new HashSet<Course>();

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}


Test类代码

import java.util.Arrays;

import java.util.Iterator;


public class Test {

public void TestAdd2() {

Student stu = new Student();

Course[] course = { new Course("1", "大学数学"), new Course("2", "大学英语"),

new Course("3", "大学语文"), new Course("4", "汇编语言") ,

new Course("5", "大学数学"), new Course("6", "大学英语"),

new Course("7", "大学语文"), new Course("8", "汇编语言")};

stu.courses.addAll(Arrays.asList(course));

System.out.println(stu.courses.size());

}

public void TestForEach2() {

Student stu = new Student();

for (Course c : stu.courses) {

System.out.println("课程:" + c.getId() + ":" + c.getName());

}

}

public void testIterator(){

Student stu = new Student();

Iterator it = stu.courses.iterator();

System.out.println("有待选课程如下:(通过迭代器访问)");

while(it.hasNext()){

Course c = (Course)it.next();

System.out.println(c.getId()+":"+c.getName());

}

}

public void testRemove(){

Student stu = new Student();

Course[] course={new Course("1", "大学数学"), new Course("2", "大学英语")};

stu.courses.removeAll(Arrays.asList(course));

System.out.println("成功删除!");

}


public static void main(String[] args) {

TestSet ts = new TestSet();

ts.TestAdd2();

ts.TestForEach2();

ts.testIterator();

ts.testRemove();

}

}

为什么Student中的courses集合没有成功的添加数据,

得出courses集合长度是1,为什么???????

输出结果为:

1

有待选课程如下:(通过迭代器访问)

成功删除!


慕粉4353249
浏览 1364回答 1
1回答

慕粉3291149

你把Student stu = new Student();定义为Test类的成员变量不然你每个方法中创建一个Student对象 ,操作的是不同的Student对象啊
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java