gpt4 book ai didi

java - 如何创建一个项目数组,其条目具有通用字段?

转载 作者:行者123 更新时间:2023-11-30 08:10:26 26 4
gpt4 key购买 nike

我有这个代码:

import java.util.*;
import java.lang.*;
import java.io.*;

class Main{
public static void main (String[] args){
Foo<String> foo = new Foo<String>(1000);
}
}

class Foo<Key extends Comparable<Key>>{
private Entry[] a;
private class Entry{
Key key;
}
public Foo(int size){
a = (Entry[])new Object[size]; // <- this is the problem
}
}

当我编译它时,我得到一个错误,说:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LFoo$Entry;
at Foo.<init>(Main.java:17)
at Main.main(Main.java:7)

我试过:

import java.util.*;
import java.lang.*;
import java.io.*;

class Main{
public static void main (String[] args){
Foo<String> foo = new Foo<String>(1000);
}
}

class Foo<Key extends Comparable<Key>>{
private Entry[] a;
private class Entry{
Key key;
}
public Foo(int size){
a = new Entry[size];
}
}

但后来我收到一条错误消息:

Main.java:17: error: generic array creation
a = new Entry[size];
^

是否可以创建该数组?

最佳答案

好吧,实际上你可以通过反射:

public class Main {
public static void main(String[] args) {
Foo<String> foo = new Foo<String>(1000);
foo.a[0] = foo.new Entry();
foo.a[0].key = "ss";
}
}

class Foo<Key extends Comparable<Key>> {
public Entry[] a;

public class Entry {
Key key;
}

public Foo(int size) {
a = (Entry[]) java.lang.reflect.Array.newInstance(Entry.class, size);
}
}

关于java - 如何创建一个项目数组,其条目具有通用字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702362/

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