gpt4 book ai didi

java - 是否可以将任何实现 java.io.serializable 的类添加到泛型 的数组列表中

转载 作者:行者123 更新时间:2023-11-29 03:28:54 26 4
gpt4 key购买 nike

描述:

我有一个 ArrayList,它接受任何实现 Serializable 的类。我什至可以将实现 Serializable 的类的实例添加到这个数组列表中,而不会出现任何编译错误。 Java 泛型如何处理将这些可序列化对象添加到此列表?

我知道我们无法定义引用 List<Object> l

但是我的 List<Serializable> serializables 没有发现任何编译问题引用。

我的第二个问题是如何检索添加到此可序列化列表的这些对象中的元素?

如果类似问题的答案已经发布,请发布您的链接。

/***Here is my main class***/

import java.io.Serializable;
import java.util.*;

public class LearnArrayList {
public static void main(String[] args) {

List<Serializable> serializables = new ArrayList<Serializable>();
serializables.add(new RandomClass1());
serializables.add(new RandomClass2());

}
}

/***Here is my RandomClass1 that I will add it to List<Serializable>***/

import java.io.Serializable;

public class RandomClass1 implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int a;
private int b;

/*Getters and setters here*/
}

/***Here is my RandomClass2 that I will add it to List<Serializable>***/
import java.io.Serializable;

public class RandomClass2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String s;

/*Getters and setters here*/
}

最佳答案

How does Java Generics handle adding these serializable objects to this List?

编译器会检查您添加的是可序列化的。

I am aware of the fact that we cannot define a reference List l

其实你可以。

However I don't see any compilation problems with my List serializables reference.

我也不明白为什么你会得到编译错误。

My second question I have here is how do I retrieve my elements in these objects that are added to this serializable list?

与处理任何列表的方式相同。使用 get(n) 或迭代它们。

But what is the right way to look at the elements in my class after retrieving the objects from my list.

正确的方法是实现程序必须执行的操作的最简单明了的方法。

关于java - 是否可以将任何实现 java.io.serializable 的类添加到泛型 <Serializable> 的数组列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com