gpt4 book ai didi

java - 通用数组如何添加set方法?

转载 作者:行者123 更新时间:2023-12-01 10:36:13 26 4
gpt4 key购买 nike

我想编写一个方法来帮助我在泛型类变量中存储一些内容。我有点不明白一个概念:(

我想编写一个方法来替换这个简单的解决方案:

a.myObject[0]=tracks;

当我将数组索引作为参数提供时,它将与其他元素一起使用

我想找出类似这个方法的东西(但作为一个设置值)。有人知道如何做吗?

E get(int i) {
return (E) myObject[i];
}

我的源代码:

import java.util.Arrays;
import java.util.List;

public class GenericArray<E>{

private Object[] myObject;

public GenericArray(int s) {
myObject = new Object[s];
}

E get(int i) {
return (E) myObject[i];
}


public static <Track> void main(String[] args) {

GenericArray a = new GenericArray(100);

List<String> tracks = Arrays.asList("One", "Two", "Three");

PlayList play = new PlayList(tracks);

a.myObject[0]=tracks;

System.out.println(a.get(0));

}

}

最佳答案

无法创建通用数组,因此将其更改为集合。我对您的代码做了一些调整:

public class GenericArray<E extends Object> {

private List<E> myObject;

public GenericArray(int s) {
//myObject = new E[s];//can not create a generic array
myObject = new ArrayList<>(s);
}

public E get(int i) {
return myObject.get(i);
}

public void set(int i, E object){
myObject.set(i, object);
}

public static void main(String[] args) {

GenericArray<Object> a = new GenericArray<>(100);

List<String> tracks = Arrays.asList("One", "Two", "Three");

PlayList play = new PlayList(tracks);

a.set(0, tracks);

System.out.println(a.get(0));

}

}

嗯...我认为这是因为集合中从未添加任何内容。 (有能力但没有要素)。我查看了有关通用数组的评论,所以这是另一个示例,这个示例应该可以工作:

public class GenericArray<E extends Object> {
private E[] myObject;

public GenericArray(Class<E> c,int s) {
//myObject = new E[s];//can not create a generic array
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
myObject = a;
}

public E get(int i) {
return myObject[i];
}

public void set(int i, E object){
myObject[i] = object;
}

public static void main(String[] args) {

GenericArray<Object> a = new GenericArray<>(Object.class,100);

List<String> tracks = Arrays.asList("One", "Two", "Three");

PlayList play = new PlayList(tracks);

a.set(0, tracks);

System.out.println(a.get(0));

}

}

关于java - 通用数组如何添加set方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34709691/

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