arraylist<student>
时间: 2023-04-23 09:02:20 浏览: 95
ArrayList<Student> 是一个泛型类,其中 Student 是指定的类型参数,表示这个 ArrayList 中存储的元素都是 Student 类型的对象。它是 Java 中的一个动态数组,可以根据需要动态地增加或减少元素的数量。在 ArrayList 中,元素的访问速度比较快,因为它是基于索引的,可以通过索引快速地访问到指定位置的元素。
相关问题
ArrayList<Student> stu=new ArrayList<>()添加对象
可以使用以下代码向 ArrayList<Student> 对象中添加一个 Student 对象:
```
Student s = new Student("John", 20); // 创建一个 Student 对象
stu.add(s); // 将该对象添加到 ArrayList<Student> 中
```
其中,Student 是一个自定义的类,代码示例中的第一行创建了一个名为 s 的 Student 对象,并指定了其姓名和年龄,第二行将该对象添加到了名为 stu 的 ArrayList<Student> 对象中。如果需要添加多个 Student 对象,可以重复以上代码多次,每次创建一个新的 Student 对象并将其添加到 ArrayList<Student> 中即可。
写入多个对象储存后,无法用ArrayList<Student> list = (ArrayList <Student>) ois.readObject();读取
这种情况可能是因为你在写入对象时使用了 ObjectOutputStream 的 writeObject 方法,但是在读取对象时使用了 ObjectInputStream 的 readObject 方法,但是没有按照写入对象的顺序读取。
如果你在写入对象时使用了 writeObject 方法,那么在读取对象时也应该按照写入对象的顺序读取,例如:
```java
// 写入对象
ArrayList<Student> list = new ArrayList<>();
// ...
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.txt"));
oos.writeObject(list);
oos.close();
// 读取对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.txt"));
ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
ois.close();
```
如果你确保按照写入对象的顺序读取,但仍然无法读取所有对象,那么可能是因为某些对象在写入时没有被正确地序列化。你可以检查一下在写入对象时是否有报错或者警告信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)